Struct Session

Source
pub struct Session(/* private fields */);
Expand description

The entrypoint of the zenoh API.

Zenoh session is instantiated using zenoh::open and it can be used to declare various entities like publishers, subscribers, or querybables, as well as issuing queries.

Session is an Arc-like type, it can be cloned, and it is closed when the last instance is dropped (see Session::close).

§Examples


let session = zenoh::open(zenoh::Config::default()).await.unwrap();
session.put("key/expression", "value").await.unwrap();

Implementations§

Source§

impl Session

Source

pub fn zid(&self) -> ZenohId

Returns the identifier of the current session. zid() is a convenient shortcut. See Session::info() and SessionInfo::zid() for more details.

Source

pub fn close(&self) -> CloseBuilder<Self>

Close the zenoh Session.

Every subscriber and queryable declared will stop receiving data, and further attempt to publish or query with the session or publishers will result in an error. Undeclaring an entity after session closing is a no-op. Session state can be checked with Session::is_closed.

Session are automatically closed when all its instances are dropped, same as Arc. You may still want to use this function to handle errors or close the session asynchronously.
Closing the session can also save bandwidth, as it avoids propagating the undeclaration of the remaining entities.

§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let subscriber = session
    .declare_subscriber("key/expression")
    .await
    .unwrap();
let subscriber_task = tokio::spawn(async move {
    while let Ok(sample) = subscriber.recv_async().await {
        println!("Received: {} {:?}", sample.key_expr(), sample.payload());
    }
});
session.close().await.unwrap();
// subscriber task will end as `subscriber.recv_async()` will return `Err`
// subscriber undeclaration has not been sent on the wire
subscriber_task.await.unwrap();
Source

pub fn is_closed(&self) -> bool

Check if the session has been closed.

§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
assert!(!session.is_closed());
session.close().await.unwrap();
assert!(session.is_closed());
Source

pub fn undeclare<'a, T>(&'a self, decl: T) -> impl Resolve<ZResult<()>> + 'a
where T: Undeclarable<&'a Session> + 'a,

Source

pub fn config(&self) -> &Notifier<Config>

Available on crate feature unstable only.

Get the current configuration of the zenoh Session.

This API has been marked as unstable: it works as advertised, but it may be changed in a future release.

The returned configuration Notifier can be used to read the current zenoh configuration through the get function or modify the zenoh configuration through the insert, or insert_json5 function.

§Examples
§Read current zenoh configuration

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let peers = session.config().get("connect/endpoints").unwrap();
§Modify current zenoh configuration

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let _ = session.config().insert_json5("connect/endpoints", r#"["tcp/127.0.0.1/7447"]"#);
Source

pub fn new_timestamp(&self) -> Timestamp

Get a new Timestamp from a Zenoh Session.

The returned timestamp has the current time, with the Session’s runtime ZenohId.

§Examples
§Read current zenoh configuration

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let timestamp = session.new_timestamp();
Source§

impl Session

Source

pub fn info(&self) -> SessionInfo

Get information about the zenoh Session.

§Examples

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

pub fn declare_subscriber<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> SubscriberBuilder<'_, 'b, DefaultHandler>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Create a Subscriber for the given key expression.

§Arguments
  • key_expr - The resourkey expression to subscribe to
§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let subscriber = session.declare_subscriber("key/expression")
    .await
    .unwrap();
tokio::task::spawn(async move {
    while let Ok(sample) = subscriber.recv_async().await {
        println!("Received: {:?}", sample);
    }
}).await;
Source

pub fn declare_queryable<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> QueryableBuilder<'_, 'b, DefaultHandler>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Create a Queryable for the given key expression.

§Arguments
  • key_expr - The key expression matching the queries the Queryable will reply to
§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let queryable = session.declare_queryable("key/expression")
    .await
    .unwrap();
tokio::task::spawn(async move {
    while let Ok(query) = queryable.recv_async().await {
        query.reply(
            "key/expression",
            "value",
        ).await.unwrap();
    }
}).await;
Source

pub fn declare_publisher<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> PublisherBuilder<'_, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Create a Publisher for the given key expression.

§Arguments
  • key_expr - The key expression matching resources to write
§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let publisher = session.declare_publisher("key/expression")
    .await
    .unwrap();
publisher.put("value").await.unwrap();
Source

pub fn declare_querier<'b, TryIntoKeyExpr>( &self, key_expr: TryIntoKeyExpr, ) -> QuerierBuilder<'_, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Available on crate feature unstable only.

Create a Querier for the given key expression.

This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
§Arguments
  • key_expr - The key expression matching resources to query
§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let querier = session.declare_querier("key/expression")
    .await
    .unwrap();
let replies = querier.get().await.unwrap();
Source

pub fn liveliness(&self) -> Liveliness<'_>

Obtain a Liveliness struct tied to this Zenoh Session.

§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let liveliness = session
    .liveliness()
    .declare_token("key/expression")
    .await
    .unwrap();
Source§

impl Session

Source

pub fn declare_keyexpr<'a, 'b: 'a, TryIntoKeyExpr>( &'a self, key_expr: TryIntoKeyExpr, ) -> impl Resolve<ZResult<KeyExpr<'b>>> + 'a
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Informs Zenoh that you intend to use key_expr multiple times and that it should optimize its transmission.

The returned KeyExpr’s internal structure may differ from what you would have obtained through a simple key_expr.try_into(), to save time on detecting the optimizations that have been associated with it.

§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let key_expr = session.declare_keyexpr("key/expression").await.unwrap();
Source

pub fn put<'a, 'b: 'a, TryIntoKeyExpr, IntoZBytes>( &'a self, key_expr: TryIntoKeyExpr, payload: IntoZBytes, ) -> SessionPutBuilder<'a, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>, IntoZBytes: Into<ZBytes>,

Put data.

§Arguments
  • key_expr - Key expression matching the resources to put
  • payload - The payload to put
§Examples
use zenoh::bytes::Encoding;

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
session
    .put("key/expression", "payload")
    .encoding(Encoding::TEXT_PLAIN)
    .await
    .unwrap();
Source

pub fn delete<'a, 'b: 'a, TryIntoKeyExpr>( &'a self, key_expr: TryIntoKeyExpr, ) -> SessionDeleteBuilder<'a, 'b>
where TryIntoKeyExpr: TryInto<KeyExpr<'b>>, <TryIntoKeyExpr as TryInto<KeyExpr<'b>>>::Error: Into<Error>,

Delete data.

§Arguments
  • key_expr - Key expression matching the resources to delete
§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
session.delete("key/expression").await.unwrap();
Source

pub fn get<'a, 'b: 'a, TryIntoSelector>( &'a self, selector: TryIntoSelector, ) -> SessionGetBuilder<'a, 'b, DefaultHandler>
where TryIntoSelector: TryInto<Selector<'b>>, <TryIntoSelector as TryInto<Selector<'b>>>::Error: Into<Error>,

Query data from the matching queryables in the system.

Unless explicitly requested via accept_replies, replies are guaranteed to have key expressions that match the requested selector.

§Arguments
  • selector - The selection of resources to query
§Examples

let session = zenoh::open(zenoh::Config::default()).await.unwrap();
let replies = session.get("key/expression").await.unwrap();
while let Ok(reply) = replies.recv_async().await {
    println!(">> Received {:?}", reply.result());
}

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Session

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<Source> AccessAs for Source

Source§

fn ref_as<T>(&self) -> <Source as IGuardRef<T>>::Guard<'_>
where Source: IGuardRef<T>, T: ?Sized,

Provides immutable access to a type as if it were its ABI-unstable equivalent.
Source§

fn mut_as<T>(&mut self) -> <Source as IGuardMut<T>>::GuardMut<'_>
where Source: IGuardMut<T>, T: ?Sized,

Provides mutable access to a type as if it were its ABI-unstable equivalent.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsNode<T> for T

Source§

fn as_node(&self) -> &T

Source§

impl<T> AsNodeMut<T> for T

Source§

fn as_node_mut(&mut self) -> &mut T

Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, As> IGuardMut<As> for T
where T: Into<As>, As: Into<T>,

Source§

type GuardMut<'a> = MutAs<'a, T, As> where T: 'a

The type of the guard which will clean up the temporary after applying its changes to the original.
Source§

fn guard_mut_inner(&mut self) -> <T as IGuardMut<As>>::GuardMut<'_>

Construct the temporary and guard it through a mutable reference.
Source§

impl<T, As> IGuardRef<As> for T
where T: Into<As>, As: Into<T>,

Source§

type Guard<'a> = RefAs<'a, T, As> where T: 'a

The type of the guard which will clean up the temporary.
Source§

fn guard_ref_inner(&self) -> <T as IGuardRef<As>>::Guard<'_>

Construct the temporary and guard it through an immutable reference.
Source§

impl<T> Includes<End> for T

Source§

type Output = End

The result
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,