### CancellationToken Example Source: https://docs.rs/zenoh/latest/src/zenoh/api/cancellation.rs.html Demonstrates how to create and use a CancellationToken to potentially interrupt a get query. This example shows basic setup for a query with a callback. ```rust /// A synchronization primitive that can be used to interrupt a get query. /// /// # Examples /// ``` /// # #[tokio::main] /// # async fn main() { /// /// let session = zenoh::open(zenoh::Config::default()).await.unwrap(); /// let mut n = 0; /// let cancellation_token = zenoh::cancellation::CancellationToken::default(); /// let queryable = session /// .get("key/expression") /// .callback_mut(move |reply| {n += 1;}) /// ``` -------------------------------- ### Declare and Query with Callback Source: https://docs.rs/zenoh/latest/src/zenoh/api/builders/querier.rs.html Demonstrates how to declare a querier, send a GET request, and process replies using a callback function. This example also shows how to set query targets and consolidation modes. ```rust use zenoh::{query::{ConsolidationMode, QueryTarget}}; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let querier = session.declare_querier("key/expression") .target(QueryTarget::All) .consolidation(ConsolidationMode::None) .await .unwrap(); let _ = querier .get() .callback(|reply| {println!("Received {:?}", reply.result());}) .await .unwrap(); ``` -------------------------------- ### Start Peer Configuration and Initialization Source: https://docs.rs/zenoh/latest/src/zenoh/net/runtime/orchestrator.rs.html Retrieves configuration for starting a peer, including listeners, direct peers, scouting settings, and connection parameters. Binds listeners and connects to specified peers before potentially starting multicast scouting. ```rust async fn start_peer(&self) -> ZResult<()> { let (listeners, peers, scouting, wait_scouting, listen, autoconnect, addr, ifaces, delay) = { let guard = &self.state.config.lock(); ( guard.listen().endpoints().peer().unwrap_or(&vec![]).clone(), guard .connect() .endpoints() .peer() .unwrap_or(&vec![]) .clone(), unwrap_or_default!(guard.scouting().multicast().enabled()), unwrap_or_default!(guard.open().return_conditions().connect_scouted()), *unwrap_or_default!(guard.scouting().multicast().listen().peer()), AutoConnect::multicast(guard, WhatAmI::Peer, self.zid().into()), unwrap_or_default!(guard.scouting().multicast().address()), unwrap_or_default!(guard.scouting().multicast().interface()), Duration::from_millis(unwrap_or_default!(guard.scouting().delay())), ) }; self.bind_listeners(&listeners).await?; self.connect_peers(&peers, false).await?; if scouting { self.start_scout(listen, autoconnect, addr, ifaces).await?; } if wait_scouting && (scouting || !peers.is_empty()) && tokio::time::timeout(delay, self.state.start_conditions.notified()) .await .is_err() && !peers.is_empty() { tracing::warn!("Scouting delay elapsed before start conditions are met."); } Ok(()) } ``` -------------------------------- ### Plugin Configuration Example Source: https://docs.rs/zenoh/latest/zenoh/config/struct.Config.html Example of how to configure plugins using the `__config__` property. This snippet shows a placeholder for REST plugin configuration. ```toml plugins: { rest: { ``` -------------------------------- ### Initiate a Query with Get Builder Source: https://docs.rs/zenoh/latest/zenoh/query/struct.Querier.html This snippet shows how to initiate a query using the `get` method, which returns a builder for customizing the query before sending it. ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let querier = session.declare_querier("key/expression").await.unwrap(); let replies = querier.get(); ``` -------------------------------- ### Explicitly Create Subscriber with Callback and Handler Source: https://docs.rs/zenoh/latest/src/zenoh/lib.rs.html This example demonstrates the explicit creation of a callback and a RingChannel handler, which are then used to configure a subscriber. This approach provides more control over the handler setup compared to the `with` method. ```rust # #[tokio::main] # async fn main() { # let session = zenoh::open(zenoh::Config::default()).await.unwrap(); use zenoh::handlers::IntoHandler; let (callback, mut ring_channel_handler) = zenoh::handlers::RingChannel::new(10).into_handler(); let subscriber = session.declare_subscriber("key/expression") .with((callback, ())) // or simply .callback(callback) .await.unwrap(); # } ``` -------------------------------- ### Declare and Configure a Querier Source: https://docs.rs/zenoh/latest/zenoh/query/struct.QuerierBuilder.html Example of declaring a querier with specific target, consolidation mode, and then performing a get operation. This snippet demonstrates the typical workflow for setting up and using a querier. ```rust use zenoh::{ query::{ConsolidationMode, QueryTarget}, }; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let querier = session.declare_querier("key/expression") .target(QueryTarget::All) .consolidation(ConsolidationMode::None) .await .unwrap(); let replies = querier.get() .parameters("value>1") .await .unwrap(); while let Ok(reply) = replies.recv_async().await { println!("Received {:?}", reply.result()) } ``` -------------------------------- ### Explicit RingChannel Setup Source: https://docs.rs/zenoh/latest/zenoh/handlers/index.html Demonstrates the explicit setup of a `RingChannel` and its handler, then uses the `with` method to associate it with a subscriber. This approach provides more control over the channel creation. ```rust use zenoh::handlers::IntoHandler; let (callback, mut ring_channel_handler) = zenoh::handlers::RingChannel::new(10).into_handler(); let subscriber = session.declare_subscriber("key/expression") .with((callback, ())) // or simply .callback(callback) .await.unwrap(); while let Ok(sample) = ring_channel_handler.recv_async().await { println!("Received: {:?}", sample); } ``` -------------------------------- ### Example: Using SessionGetBuilder for a GET operation Source: https://docs.rs/zenoh/latest/src/zenoh/api/builders/query.rs.html Demonstrates how to use the SessionGetBuilder to perform a GET operation on a key expression, specifying the target, consolidation mode, and processing the received replies. ```rust use zenoh::{query::{ConsolidationMode, QueryTarget}}; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let replies = session .get("key/expression?value>1") .target(QueryTarget::All) .consolidation(ConsolidationMode::None) .await .unwrap(); while let Ok(reply) = replies.recv_async().await { println!("Received {:?}", reply.result()) } ``` -------------------------------- ### Example of getting liveliness tokens Source: https://docs.rs/zenoh/latest/src/zenoh/api/builders/liveliness.rs.html Demonstrates how to open a Zenoh session, query for liveliness tokens using a key expression, and process the received tokens asynchronously. ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let tokens = session .liveliness() .get("key/expression") .await .unwrap(); while let Ok(token) = tokens.recv_async().await { match token.result() { Ok(sample) => println!("Alive token ('{}')", sample.key_expr().as_str()), Err(err) => println!("Received (ERROR: '{:?}')", err.payload()), } } ``` -------------------------------- ### CancellationToken Example Source: https://docs.rs/zenoh/latest/zenoh/cancellation/struct.CancellationToken.html Example demonstrating how to use CancellationToken to interrupt a get query. ```APIDOC ## Examples ``` let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let mut n = 0; let cancellation_token = zenoh::cancellation::CancellationToken::default(); let queryable = session .get("key/expression") .callback_mut(move |reply| {n += 1;}) .cancellation_token(cancellation_token.clone()) .await .unwrap(); // this call will interrupt query, after it returns it is guaranteed that callback will no longer be called cancellation_token.cancel().await; ``` ``` -------------------------------- ### Example Usage of CancellationToken Source: https://docs.rs/zenoh/latest/zenoh/cancellation/struct.CancellationToken.html Demonstrates how to create a CancellationToken, associate it with a get query, and then cancel the query. The callback is executed until cancellation is confirmed. ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let mut n = 0; let cancellation_token = zenoh::cancellation::CancellationToken::default(); let queryable = session .get("key/expression") .callback_mut(move |reply| {n += 1;}) .cancellation_token(cancellation_token.clone()) .await .unwrap(); // this call will interrupt query, after it returns it is guaranteed that callback will no longer be called cancellation_token.cancel().await; ``` -------------------------------- ### Load and Start Plugin Source: https://docs.rs/zenoh/latest/src/zenoh/net/runtime/adminspace.rs.html Handles loading and starting a plugin, with checks for already loaded or started plugins. Logs warnings if a plugin is already loaded or started, or if plugin loading is disabled. ```rust let mut loaded = if let Some(loaded) = declared.loaded_mut() { tracing::warn!( "Plugin `{}` was already loaded from {}", loaded.id(), loaded.path() ); loaded } else { match declared.load()? { Some(loaded) => loaded, None => { tracing::warn!( "Plugin `{}` will not be loaded as plugin loading is disabled", config.name ); return Ok(()) } } }; if let Some(started) = loaded.started_mut() { tracing::warn!("Plugin `{}` was already started", started.id()); } else { let started = loaded.start(start_args)?; tracing::info!( "Successfully started plugin `{}` from {}", started.id(), started.path() ); }; Ok(()) } ``` -------------------------------- ### Open zenoh Session with Default Configuration Source: https://docs.rs/zenoh/latest/zenoh/fn.open.html Opens a zenoh session using the default configuration. This is a simple way to get started with zenoh. ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); ``` -------------------------------- ### Start Router Configuration and Initialization Source: https://docs.rs/zenoh/latest/src/zenoh/net/runtime/orchestrator.rs.html Retrieves configuration for starting a router, including listeners, direct peers, and scouting settings. This snippet focuses on fetching the configuration values needed for router initialization. ```rust async fn start_router(&self) -> ZResult<()> { let (listeners, peers, scouting, listen, autoconnect, addr, ifaces, delay) = { let guard = &self.state.config.lock(); ( guard .listen() .endpoints() .router() .unwrap_or(&vec![]) .clone(), ``` -------------------------------- ### PeersZenohIdBuilder Usage Example Source: https://docs.rs/zenoh/latest/zenoh/session/struct.PeersZenohIdBuilder.html This example demonstrates how to obtain a PeersZenohIdBuilder from a zenoh session and iterate through the ZenohIds of connected peers. ```APIDOC ## §Examples ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let zid = session.info().zid().await; let mut peers_zid = session.info().peers_zid().await; while let Some(peer_zid) = peers_zid.next() {} ``` ``` -------------------------------- ### Scout with Receiver Source: https://docs.rs/zenoh/latest/src/zenoh/api/scouting.rs.html This example shows how to create a scout that uses a receiver (e.g., from `flume`) to get 'Hello' messages. ```APIDOC ## scout with receiver ### Description Creates a scout that sends 'Hello' messages and provides a receiver to retrieve incoming 'Hello' messages. ### Method Signature `zenoh::scout(what: WhatAmIMatcher, config: Config) -> ScoutBuilder` ### Parameters - `what` (WhatAmIMatcher): Specifies the types of entities to scout for (e.g., `WhatAmI::Peer | WhatAmI::Router`). - `config` (Config): Zenoh configuration settings. ### Returns A `ScoutBuilder` that can be configured with a receiver channel. ### Example ```rust # #[tokio::main] # async fn main() { use zenoh::config::WhatAmI; let receiver = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, zenoh::Config::default()) .with(flume::bounded(32)) .await .unwrap(); while let Ok(hello) = receiver.recv_async().await { println!("{}", hello); } # } ``` ``` -------------------------------- ### Example Zenoh Configuration File Source: https://docs.rs/zenoh/latest/zenoh/struct.Config.html An example JSON5 configuration file for Zenoh. It demonstrates various settings including node mode, metadata, connection endpoints, and listening endpoints. Note that the 'id' field is commented out and requires a unique hexadecimal value. ```json5 /// This file attempts to list and document available configuration elements. /// For a more complete view of the configuration's structure, check out `zenoh/src/config.rs`'s `Config` structure. /// Note that the values here are correctly typed, but may not be sensible, so copying this file to change only the parts that matter to you is not good practice. { /// The identifier (as unsigned 128bit integer in hexadecimal lowercase - leading zeros are not accepted) /// that zenoh runtime will use. /// If not set, a random unsigned 128bit integer will be used. /// WARNING: this id must be unique in your zenoh network. // id: "1234567890abcdef", /// The node's mode (router, peer or client) mode: "peer", /// The node's metadata (name, location, DNS name, etc.) Arbitrary JSON data not interpreted by zenoh and available in admin space @//router, @//peer or @//client metadata: { name: "strawberry", location: "Penny Lane", }, /// Which endpoints to connect to. E.g. tcp/localhost:7447. /// By configuring the endpoints, it is possible to tell zenoh which router/peer to connect to at startup. /// /// For TCP/UDP on Linux, it is possible additionally specify the interface to be connected to: /// E.g. tcp/192.168.0.1:7447#iface=eth0, for connect only if the IP address is reachable via the interface eth0 /// /// It is also possible to specify a priority range and/or a reliability setting to be used on the link. /// For example `tcp/localhost?prio=6-7;rel=0` assigns priorities "data_low" and "background" to the established link. /// /// For TCP and TLS links, it is possible to specify the TCP buffer sizes: /// E.g. tcp/192.168.0.1:7447#so_sndbuf=65000;so_rcvbuf=65000 /// For TCP, UDP, Quic and TLS links, it is possible to specify a `bind` address for the local socket: /// E.g. tcp/192.168.0.1:7447#bind=192.168.0.1:0 /// Note!: Currently it is unsupported to specify both `bind` and `iface`. /// /// For TCP/UDP links, it's possible to specify the DSCP field of the IP header: /// E.g. tcp/192.168.0.1:7447#dscp=0x08 connect: { /// timeout waiting for all endpoints connected (0: no retry, -1: infinite timeout) /// Accepts a single value (e.g. timeout_ms: 0) /// or different values for router, peer and client (e.g. timeout_ms: { router: -1, peer: -1, client: 0 }). timeout_ms: { router: -1, peer: -1, client: 0 }, /// The list of endpoints to connect to. /// Accepts a single list (e.g. endpoints: ["tcp/10.10.10.10:7447", "tcp/11.11.11.11:7447"]) /// or different lists for router, peer and client (e.g. endpoints: { router: ["tcp/10.10.10.10:7447"], peer: ["tcp/11.11.11.11:7447"] }). /// /// See https://docs.rs/zenoh/latest/zenoh/config/struct.EndPoint.html endpoints: [ // "/
" ], /// Global connect configuration, /// Accepts a single value or different values for router, peer and client. /// The configuration can also be specified for the separate endpoint /// it will override the global one /// E.g. tcp/192.168.0.1:7447#retry_period_init_ms=20000;retry_period_max_ms=10000" /// exit from application, if timeout exceed exit_on_failure: { router: false, peer: false, client: true }, /// connect establishing retry configuration retry: { /// initial wait timeout until next connect try period_init_ms: 1000, /// maximum wait timeout until next connect try period_max_ms: 4000, /// increase factor for the next timeout until nexti connect try period_increase_factor: 2, }, }, /// Which endpoints to listen on. E.g. tcp/0.0.0.0:7447. /// By configuring the endpoints, it is possible to tell zenoh which are the endpoints that other routers, /// peers, or client can use to establish a zenoh session. /// /// For TCP/UDP on Linux, it is possible additionally specify the interface to be listened to: /// E.g. tcp/0.0.0.0:7447#iface=eth0, for listen connection only on eth0 /// /// It is also possible to specify a priority range and/or a reliability setting to be used on the link. /// For example `tcp/localhost?prio=6-7;rel=0` assigns priorities "data_low" and "background" to the established link. /// /// For TCP and TLS links, it is possible to specify the TCP buffer sizes: /// E.g. tcp/192.168.0.1:7447#so_sndbuf=65000;so_rcvbuf=65000 /// } ``` -------------------------------- ### Configure and Execute a GET Operation Source: https://docs.rs/zenoh/latest/zenoh/query/struct.QuerierGetBuilder.html This snippet demonstrates how to configure a GET operation using QuerierGetBuilder, specifying the target and consolidation mode, and then receiving replies asynchronously. ```rust use zenoh::{ query::{ConsolidationMode, QueryTarget}, }; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let querier = session.declare_querier("key/expression") .target(QueryTarget::All) .consolidation(ConsolidationMode::None) .await .unwrap(); let replies = querier .get() .parameters("value>1") .await .unwrap(); while let Ok(reply) = replies.recv_async().await { println!("Received {:?}", reply.result()) } ``` -------------------------------- ### Start Zenoh Runtime Based on Role Source: https://docs.rs/zenoh/latest/src/zenoh/net/runtime/orchestrator.rs.html Determines the role of the Zenoh instance (Client, Peer, or Router) and calls the appropriate startup function. This is the main entry point for starting the runtime. ```rust pub async fn start(&mut self) -> ZResult<()> { match self.whatami() { WhatAmI::Client => self.start_client().await, WhatAmI::Peer => self.start_peer().await, WhatAmI::Router => self.start_router().await, } } ``` -------------------------------- ### Example Usage of Zenoh Scout Source: https://docs.rs/zenoh/latest/src/zenoh/api/scouting.rs.html This example demonstrates how to use the `scout` function to find peers and routers. It continuously receives and prints information about discovered entities until the receiver is closed. ```rust # #[tokio::main] # async fn main() { use zenoh::config::WhatAmI; let receiver = zenoh::scout(WhatAmI::Peer | WhatAmI::Router, zenoh::Config::default()) .await .unwrap(); while let Ok(hello) = receiver.recv_async().await { println!("{}", hello); } # } ``` -------------------------------- ### QuerierGetBuilder::get Source: https://docs.rs/zenoh/latest/zenoh/query/struct.QuerierGetBuilder.html Initiates a 'get' operation using the QuerierGetBuilder. This is the primary method to start building a get query. ```APIDOC ## QuerierGetBuilder::get ### Description Initiates a `get` operation using the `QuerierGetBuilder`. This method is the entry point for configuring and executing a get query. ### Method This is a method call on a `Querier` object, not a direct HTTP endpoint. ### Endpoint N/A (SDK method) ### Parameters This method does not take direct parameters but is part of a builder pattern. ### Request Example ```rust let replies = querier.get().await.unwrap(); ``` ### Response Returns a `QuerierGetBuilder` instance configured for the `get` operation, which can then be further customized or executed. ``` -------------------------------- ### GET Operation with Cancellation Token Source: https://docs.rs/zenoh/latest/zenoh/query/struct.QuerierGetBuilder.html This example shows how to use a cancellation token to interrupt a GET operation. A separate task is spawned to cancel the operation after a delay. ```rust use zenoh::{ query::{ConsolidationMode, QueryTarget}, }; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let querier = session.declare_querier("key/expression") .target(QueryTarget::All) .consolidation(ConsolidationMode::None) .await .unwrap(); let ct = zenoh::cancellation::CancellationToken::default(); let _ = querier .get() .callback(|reply| {println!("Received {:?}", reply.result());}) .cancellation_token(ct.clone()) .await .unwrap(); tokio::task::spawn(async move { tokio::time::sleep(std::time::Duration::from_secs(10)).await; ct.cancel().await.unwrap(); }); ``` -------------------------------- ### Example Zenoh Configuration File Source: https://docs.rs/zenoh/latest/zenoh/config/struct.Config.html Illustrates available configuration elements for Zenoh. Use this as a template to modify specific settings. ```json { /// The identifier (as unsigned 128bit integer in hexadecimal lowercase - leading zeros are not accepted) /// that zenoh runtime will use. /// If not set, a random unsigned 128bit integer will be used. /// WARNING: this id must be unique in your zenoh network. // id: "1234567890abcdef", /// The node's mode (router, peer or client) mode: "peer", /// The node's metadata (name, location, DNS name, etc.) Arbitrary JSON data not interpreted by zenoh and available in admin space @//router, @//peer or @//client metadata: { name: "strawberry", location: "Penny Lane", }, /// Which endpoints to connect to. E.g. tcp/localhost:7447. /// By configuring the endpoints, it is possible to tell zenoh which router/peer to connect to at startup. /// /// For TCP/UDP on Linux, it is possible additionally specify the interface to be connected to: /// E.g. tcp/192.168.0.1:7447#iface=eth0, for connect only if the IP address is reachable via the interface eth0 /// /// It is also possible to specify a priority range and/or a reliability setting to be used on the link. /// For example `tcp/localhost?prio=6-7;rel=0` assigns priorities "data_low" and "background" to the established link. /// /// For TCP and TLS links, it is possible to specify the TCP buffer sizes: /// E.g. tcp/192.168.0.1:7447#so_sndbuf=65000;so_rcvbuf=65000 /// For TCP, UDP, Quic and TLS links, it is possible to specify a `bind` address for the local socket: /// E.g. tcp/192.168.0.1:7447#bind=192.168.0.1:0 /// Note!: Currently it is unsupported to specify both `bind` and `iface`. /// /// For TCP/UDP links, it's possible to specify the DSCP field of the IP header: /// E.g. tcp/192.168.0.1:7447#dscp=0x08 connect: { /// timeout waiting for all endpoints connected (0: no retry, -1: infinite timeout) /// Accepts a single value (e.g. timeout_ms: 0) /// or different values for router, peer and client (e.g. timeout_ms: { router: -1, peer: -1, client: 0 }). timeout_ms: { router: -1, peer: -1, client: 0 }, /// The list of endpoints to connect to. /// Accepts a single list (e.g. endpoints: ["tcp/10.10.10.10:7447", "tcp/11.11.11.11:7447"]) /// or different lists for router, peer and client (e.g. endpoints: { router: ["tcp/10.10.10.10:7447"], peer: ["tcp/11.11.11.11:7447"] }). /// /// See https://docs.rs/zenoh/latest/zenoh/config/struct.EndPoint.html endpoints: [ // "/
" ], /// Global connect configuration, /// Accepts a single value or different values for router, peer and client. /// The configuration can also be specified for the separate endpoint /// it will override the global one /// E.g. tcp/192.168.0.1:7447#retry_period_init_ms=20000;retry_period_max_ms=10000" /// exit from application, if timeout exceed exit_on_failure: { router: false, peer: false, client: true }, /// connect establishing retry configuration retry: { /// initial wait timeout until next connect try period_init_ms: 1000, /// maximum wait timeout until next connect try period_max_ms: 4000, /// increase factor for the next timeout until nexti connect try period_increase_factor: 2, }, }, /// Which endpoints to listen on. E.g. tcp/0.0.0.0:7447. /// By configuring the endpoints, it is possible to tell zenoh which are the endpoints that other routers, /// peers, or client can use to establish a zenoh session. /// /// For TCP/UDP on Linux, it is possible additionally specify the interface to be listened to: /// E.g. tcp/0.0.0.0:7447#iface=eth0, for listen connection only on eth0 /// /// It is also possible to specify a priority range and/or a reliability setting to be used on the link. /// For example `tcp/localhost?prio=6-7;rel=0` assigns priorities "data_low" and "background" to the established link. /// /// For TCP and TLS links, it is possible to specify the TCP buffer sizes: /// E.g. tcp/192.168.0.1:7447#so_sndbuf=65000;so_rcvbuf=65000 /// } ``` -------------------------------- ### Open a Zenoh Session and Put Data Source: https://docs.rs/zenoh/latest/src/zenoh/api/session.rs.html Demonstrates how to open a Zenoh session with default configuration and then put a key-value pair. This is a common starting point for many Zenoh applications. ```rust # #[tokio::main] # async fn main() { let session = zenoh::open(zenoh::Config::default()).await.unwrap(); session.put("key/expression", "value").await.unwrap(); # } ``` -------------------------------- ### Execute GET Operation and Receive Replies Source: https://docs.rs/zenoh/latest/src/zenoh/api/builders/querier.rs.html Configures and executes a GET operation using a querier, returning a handler that yields replies. This example demonstrates setting query parameters and iterating through received replies. ```rust # #[tokio::main] # async fn main() { # use zenoh::{query::{ConsolidationMode, QueryTarget}}; # # let session = zenoh::open(zenoh::Config::default()).await.unwrap(); # let querier = session.declare_querier("key/expression") # .target(QueryTarget::All) # .consolidation(ConsolidationMode::None) # .await # .unwrap(); # let replies = querier # .get() # .parameters("value>1") # .await # .unwrap(); # while let Ok(reply) = replies.recv_async().await { # println!("Received {:?}", reply.result()) # } # } ``` -------------------------------- ### Declare and Query with Zenoh Source: https://docs.rs/zenoh/latest/src/zenoh/api/builders/querier.rs.html Demonstrates how to declare a querier, set query targets and consolidation modes, and then retrieve replies asynchronously. This example shows the typical workflow for querying data in Zenoh. ```rust /// let session = zenoh::open(zenoh::Config::default()).await.unwrap(); /// let querier = session.declare_querier("key/expression") /// .target(QueryTarget::All) /// .consolidation(ConsolidationMode::None) /// .await /// .unwrap(); /// let replies = querier /// .get() /// .with(flume::bounded(32)) /// .await /// .unwrap(); /// while let Ok(reply) = replies.recv_async().await { /// println!("Received {:?}", reply.result()); /// } /// # } ``` -------------------------------- ### Get Element Offset with Unaligned Reference Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.zshmmut.html Demonstrates `element_offset` returning `None` when the provided reference does not point to the start of an element, such as when it points between elements. ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Example of Joining KeyExprs Source: https://docs.rs/zenoh/latest/src/zenoh/api/key_expr.rs.html Demonstrates how to join two KeyExpr instances using the `join` method, resulting in a new KeyExpr with a '/' separator. ```rust let prefix = KeyExpr::try_from("some/prefix").unwrap(); let suffix = KeyExpr::try_from("some/suffix").unwrap(); let join = prefix.join(&suffix).unwrap(); assert_eq!(join.as_str(), "some/prefix/some/suffix"); ``` -------------------------------- ### ZBytes Examples Source: https://docs.rs/zenoh/latest/zenoh/bytes/struct.ZBytes.html Illustrates how to create, convert, and use ZBytes with readers and writers. ```APIDOC ## §Examples `ZBytes` can be converted from/to raw bytes: ```rust use std::borrow::Cow; use zenoh::bytes::ZBytes; let buf = b"some raw bytes"; let payload = ZBytes::from(buf); assert_eq!(payload.to_bytes(), buf.as_slice()); ``` Create a `ZBytes` with a writer and read it back with a reader: ```rust use std::io::{Read, Write}; use zenoh::bytes::ZBytes; let mut writer = ZBytes::writer(); writer.write_all(b"some raw bytes").unwrap(); let payload = writer.finish(); let mut reader = payload.reader(); let mut buf = [0; 14]; reader.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"some raw bytes"); ``` ``` -------------------------------- ### Get Listening Locators Source: https://docs.rs/zenoh/latest/src/zenoh/api/info.rs.html Retrieve the locators on which the current zenoh Session is listening. This example prints the list of locators, typically showing the address and port. ```rust # #[tokio::main] # async fn main() { let session = zenoh::open(zenoh::Config::default()).await.unwrap(); println!("{:?}", session.info().locators().await); // print ["tcp/127.0.0.1:7447"] # } ``` -------------------------------- ### Declare and Configure Publisher Source: https://docs.rs/zenoh/latest/zenoh/pubsub/struct.PublisherBuilder.html Demonstrates how to open a Zenoh session, declare a publisher with a key expression, and set the congestion control policy to 'Block'. This is a common pattern for setting up publishers with specific QoS. ```rust use zenoh::qos::CongestionControl; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let publisher = session .declare_publisher("key/expression") .congestion_control(CongestionControl::Block) .await .unwrap(); ``` -------------------------------- ### String Length Example Source: https://docs.rs/zenoh/latest/zenoh/key_expr/struct.OwnedNonWildKeyExpr.html Demonstrates how to get the byte length of a string slice. Note that this counts bytes, not characters, which may differ for multi-byte UTF-8 characters. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### Example: Aligning size with AllocAlignment Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.AllocAlignment.html Demonstrates how to use `align_size` to align an initial size to a specified byte alignment. Requires the 'unstable' feature. ```rust use zenoh_shm::api::provider::types::AllocAlignment; let alignment = AllocAlignment::new(2).unwrap(); // 4-byte alignment let initial_size = 7.try_into().unwrap(); let aligned_size = alignment.align_size(initial_size); assert_eq!(aligned_size.get(), 8); ``` -------------------------------- ### init Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.GarbageCollect.html Initializes a new instance of the type. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer and returns a pointer to the allocated memory. ``` -------------------------------- ### Sample Initialization and Access Source: https://docs.rs/zenoh/latest/zenoh/sample/struct.SampleBuilderPut.html Provides methods for initializing a sample with given parameters and accessing its data. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters - **init** (::Init) - Description of the initializer. ### Returns - usize - A pointer to the initialized object. ``` ```APIDOC ## unsafe fn deref<'a, T>(ptr: usize) -> &'a T ### Description Dereferences the given pointer to provide immutable access to the object. ### Parameters - **ptr** (usize) - The pointer to the object. ### Returns - &'a T - An immutable reference to the object. ``` ```APIDOC ## unsafe fn deref_mut<'a, T>(ptr: usize) -> &'a mut T ### Description Mutably dereferences the given pointer to provide mutable access to the object. ### Parameters - **ptr** (usize) - The pointer to the object. ### Returns - &'a mut T - A mutable reference to the object. ``` ```APIDOC ## unsafe fn drop(ptr: usize) ### Description Drops the object pointed to by the given pointer, releasing its resources. ### Parameters - **ptr** (usize) - The pointer to the object to be dropped. ``` -------------------------------- ### Get Element Offset Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.zshmmut.html Determines the index of an element reference within a slice using pointer arithmetic. Returns `None` if the element reference is not aligned with the start of an element. Panics if `T` is zero-sized. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### Get Suffix of Resource Expression Source: https://docs.rs/zenoh/latest/src/zenoh/net/routing/dispatcher/resource.rs.html Returns the suffix part of the resource's expression string. The suffix is determined by the `suffix` field, which indicates the starting index of the suffix within the `expr` string. ```rust pub fn suffix(&self) -> &str { &self.expr[self.suffix..] } ``` -------------------------------- ### Open Zenoh Session Source: https://docs.rs/zenoh/latest/zenoh Demonstrates how to open a Zenoh session with default configuration. ```APIDOC ## Open Zenoh Session ### Description Opens a new Zenoh session using the default configuration. This is the primary entry point for interacting with the Zenoh network. ### Method `open` function from the `zenoh` crate. ### Parameters - `config`: A `zenoh::Config` object. `zenoh::Config::default()` uses default settings. ### Request Example ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); ``` ### Response - `session`: A `Session` object representing the connection to the Zenoh network. ``` -------------------------------- ### Example: Writing and iterating over ZBytes slices Source: https://docs.rs/zenoh/latest/src/zenoh/api/bytes.rs.html Demonstrates how to use `ZBytes::writer()` to append byte slices and then iterate over them using `slices()`. It also shows how to collect these slices into a single `Vec` for verification. ```rust use std::io::Write; use zenoh::bytes::ZBytes; let buf1: Vec = vec![1, 2, 3]; let buf2: Vec = vec![4, 5, 6, 7, 8]; let mut writer = ZBytes::writer(); writer.write(&buf1); writer.write(&buf2); let zbytes = writer.finish(); // Access the raw content for slice in zbytes.slices() { println!("{:02x?}", slice); } // Concatenate input in a single vector let buf: Vec = buf1.into_iter().chain(buf2.into_iter()).collect(); // Concatenate raw bytes in a single vector let out: Vec = zbytes.slices().fold(Vec::new(), |mut b, x| { b.extend_from_slice(x); b }); // The previous line is the equivalent of // let out: Vec = zbs.into(); assert_eq!(buf, out); ``` -------------------------------- ### Get Element Offset in Slice Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.zshm.html Returns the index of an element reference within a slice. Returns `None` if the element reference does not point to the start of an element. Useful for extending slice iterators. Does not compare elements. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Iterate over all links in a session Source: https://docs.rs/zenoh/latest/zenoh/session/struct.LinksBuilder.html This example demonstrates how to open a zenoh session, retrieve all established links, and print the source and destination of each link. ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let links = session.info().links().await; for link in links { println!("Link: {} -> {}", link.src(), link.dst()); } ``` -------------------------------- ### GET Operation with Mutable Callback Source: https://docs.rs/zenoh/latest/zenoh/query/struct.QuerierGetBuilder.html This example uses a mutable callback to process replies, ensuring that the callback is never called concurrently. It's suitable for scenarios where the callback needs to modify shared state. ```rust use zenoh::{ query::{ConsolidationMode, QueryTarget}, }; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let querier = session.declare_querier("key/expression") .target(QueryTarget::All) .consolidation(ConsolidationMode::None) .await .unwrap(); let mut n = 0; let _ = querier .get() .callback_mut(move |reply| {n += 1;}) .await .unwrap(); ``` -------------------------------- ### Sample Methods Source: https://docs.rs/zenoh/latest/src/zenoh/api/sample.rs.html Provides access to the data and metadata associated with a Zenoh sample. ```APIDOC ## Sample Methods ### Description Provides access to the data and metadata associated with a Zenoh sample. ### Methods #### `source_info()` Gets info on the source of this Sample. - **Returns**: `Option<&SourceInfo>` - An optional reference to the source information. #### `attachment()` Gets the optional sample attachment as bytes. - **Returns**: `Option<&ZBytes>` - An optional reference to the sample attachment bytes. #### `attachment_mut()` Gets a mutable reference to the optional sample attachment bytes. - **Returns**: `Option<&mut ZBytes>` - A mutable reference to the sample attachment bytes. #### `empty()` Constructs an uninitialized empty Sample. - **Returns**: `Self` - An empty Sample instance. #### `from_push()` Internal method to construct a Sample from a push operation. - **Parameters**: - `key_expr`: `KeyExpr<'static>` - The key expression for the sample. - `qos`: `push::ext::QoSType` - The Quality of Service settings. - `body`: `&mut PushBody` - The mutable reference to the push body containing the data. - `reliability`: `Reliability` (cfg(feature = "unstable")) - The reliability setting. - **Returns**: `Self` - The constructed Sample instance. ``` -------------------------------- ### get Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.GarbageCollect.html Gets the current value. ```APIDOC ## fn get(&self) -> T ### Description Returns the current value. ``` -------------------------------- ### Reply to a Query with Sample Source: https://docs.rs/zenoh/latest/src/zenoh/api/queryable.rs.html Demonstrates sending a `Sample` as a reply to a query using `reply_sample`. This is intended for internal use. ```rust # use zenoh::sample::Sample; # #[tokio::main] # async fn main() { let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let queryable = session .declare_queryable("key/expression") .callback(move |query| { query.reply_sample(Sample::empty()); }) .await .unwrap(); # session.get("key/expression").await.unwrap(); # } ``` -------------------------------- ### Runtime Start Conditions Access Source: https://docs.rs/zenoh/latest/src/zenoh/net/runtime/mod.rs.html Provides access to the start conditions of the runtime, which may include dependencies or prerequisites for starting certain components. ```rust pub(crate) fn start_conditions(&self) -> &Arc { self.state.start_conditions() } ``` -------------------------------- ### From> for Sample Source: https://docs.rs/zenoh/latest/zenoh/sample/struct.SampleBuilder.html Converts a SampleBuilder instance into a Sample. ```APIDOC ## fn from(sample_builder: SampleBuilder) -> Self ### Description Converts a `SampleBuilder` instance into a `Sample`. ### Parameters - **sample_builder**: The `SampleBuilder` instance to convert. ### Returns A `Sample` instance. ``` -------------------------------- ### LivelinessTokenUndeclaration Usage Example Source: https://docs.rs/zenoh/latest/zenoh/liveliness/struct.LivelinessTokenUndeclaration.html This example demonstrates how to declare a liveliness token and then undeclare it using the LivelinessTokenUndeclaration. ```APIDOC ## LivelinessTokenUndeclaration Usage Example This example demonstrates how to declare a liveliness token and then undeclare it using the LivelinessTokenUndeclaration. ### Code ```rust let session = zenoh::open(zenoh::Config::default()).await.unwrap(); let liveliness = session .liveliness() .declare_token("key/expression") .await .unwrap(); liveliness.undeclare().await.unwrap(); ``` ``` -------------------------------- ### Loading Configuration from File Source: https://docs.rs/zenoh/latest/src/zenoh/api/config.rs.html Loads the Zenoh configuration from a specified file path. ```APIDOC ## `Config::from_file(path)` ### Description Loads the Zenoh configuration from the file at the given `path`. ### Method `Config::from_file>(path: P)` ### Parameters #### Path Parameters - **path** (P): A type that can be converted into a `Path`, specifying the location of the configuration file. ### Returns - `ZResult`: A `ZResult` containing the loaded `Config` object on success, or an error if the file cannot be read or parsed. ``` -------------------------------- ### Example of Session Put with Configuration Source: https://docs.rs/zenoh/latest/src/zenoh/api/builders/publisher.rs.html Demonstrates how to use the `Session::put` method to send data with specified encoding and congestion control. The operation is awaited to ensure completion. ```rust use zenoh::{bytes::Encoding, qos::CongestionControl}; let session = zenoh::open(zenoh::Config::default()).await.unwrap(); session .put("key/expression", "payload") .encoding(Encoding::TEXT_PLAIN) .congestion_control(CongestionControl::Block) .await .unwrap(); ``` -------------------------------- ### get Source: https://docs.rs/zenoh/latest/zenoh/shm/struct.ZShm.html Safely gets a reference to an element or subslice by index or range. Returns None if the index is out of bounds. ```APIDOC ## pub fn get(&self, index: I) -> Option<&>::Output> ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or `None` if out of bounds. If given a range, returns the subslice corresponding to that range, or `None` if out of bounds. ### Parameters * `index`: `I` where `I: SliceIndex<[T]>` - The index or range to access. ### Returns * `Option<&>::Output>` - A reference to the element or subslice, or `None` if out of bounds. ```