API Reference
module zenoh
- final exception zenoh.ZError
Exception raised for Zenoh-related errors.
This exception is raised by various Zenoh operations when they encounter errors, such as invalid
KeyExprinstances or connection failures.To handle ZError, wrap Zenoh operations in try-except blocks:
try: ke = KeyExpr("invalid/key") except ZError as e: print(f"Error: {e}") # Get error message
The error message can be accessed via str(e) or by printing the exception directly.
- final class zenoh.CancellationToken
Cancellation token that can be used for interrupting GET queries. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Return type:
Self
- cancel()
Interrupt all associated GET queries. If the direct query callback is being executed, the call blocks until execution of callback finishes and its corresponding drop method returns (if any).
Once token is cancelled, all new associated GET queries will cancel automatically.
- property is_cancelled: bool
Return true if token was cancelled, false otherwise.
- final class zenoh.Config
The main configuration structure for Zenoh.
Zenoh configuration can be loaded from various sources:
From a specific file path using
from_file().From a file specified by the ZENOH_CONFIG environment variable using
from_env().From a JSON5 string using
from_json5().
Configuration values can be retrieved as JSON using
get_json()and modified usinginsert_json5().For detailed format information, see: https://docs.rs/zenoh/latest/zenoh/config/struct.Config.html
- Return type:
Self
- classmethod from_env()
Load configuration from the file path specified in the ZENOH_CONFIG environment variable.
- Return type:
Self
- classmethod from_file(path)
Load configuration from the file at path.
- Parameters:
path (str | Path) –
- Return type:
Self
- classmethod from_json5(json)
Load configuration from the JSON5 string json.
- Parameters:
json (str) –
- Return type:
Self
- get_json(key)
Returns a JSON string containing the configuration at key.
- Parameters:
key (str) –
- Return type:
Any
- insert_json5(key, value)
Inserts configuration value value at key.
- Parameters:
key (str) –
value (Any) –
- final enum zenoh.CongestionControl(value)
Congestion control strategy.
This parameter controls how messages are handled when a node’s transmission queue is full. Set this when declaring publishers/queriers or in put, get, delete, and reply operations to specify congestion behavior. It can also be retrieved from
SampleandPublisherobjects.- See also:
Parameters in:
Session.declare_publisher(),Session.declare_querier(),Session.put(),Session.delete(),Session.get(),Query.reply(),Query.reply_del()Properties in:
Sample.congestion_control,Publisher.congestion_control
Valid values are as follows:
- DROP = <CongestionControl.DROP: 1>
When transmitting a message in a node with a full queue, the node may drop the message.
- BLOCK = <CongestionControl.BLOCK: 2>
When transmitting a message in a node with a full queue, the node will wait for queue to progress.
- BLOCK_FIRST = <CongestionControl.BLOCK_FIRST: 3>
When transmitting a message in a node with a full queue, the node will wait for queue to progress, but only for the first message sent with this strategy; other messages will be dropped.
- final enum zenoh.ConsolidationMode(value)
The kind of consolidation to apply to a query.
Consolidation determines how multiple samples for the same key are handled during query operations, balancing between latency and bandwidth efficiency.
- See also:
Parameters in:
Session.get(),Session.declare_querier()
Valid values are as follows:
- AUTO = <ConsolidationMode.AUTO: 1>
Apply automatic consolidation based on queryable’s preferences.
- NONE = <ConsolidationMode.NONE: 2>
No consolidation applied: multiple samples may be received for the same key-timestamp.
- MONOTONIC = <ConsolidationMode.MONOTONIC: 3>
Monotonic consolidation immediately forwards samples, except if one with an equal or more recent timestamp has already been sent with the same key.
This optimizes latency while potentially reducing bandwidth. Note that this doesn’t cause re-ordering, but drops the samples for which a more recent timestamp has already been observed with the same key.
- LATEST = <ConsolidationMode.LATEST: 4>
Holds back samples to only send the set of samples that had the highest timestamp for their key.
- final class zenoh.Encoding(encoding=None)
Encoding information for Zenoh payloads.
Represents how data should be interpreted by the application, similar to HTTP Content-type. Encodings use MIME-like format:
type/subtype[;schema].Predefined class attributes are provided for common encodings (e.g.,
ZENOH_BYTES,APPLICATION_JSON). Using these is more efficient than custom strings.See also: Encoding
- Parameters:
encoding (str | None) –
- Return type:
Self
- with_schema(schema)
Set a schema to this encoding. Zenoh does not define what a schema is and its semantics are left to the implementer. E.g. a common schema for text/plain encoding is utf-8.
- Parameters:
schema (str) –
- Return type:
Self
- APPLICATION_CBOR: Self
A Concise Binary Object Representation (CBOR)-encoded data.
Constant alias for string: “application/cbor”.
- APPLICATION_CDR: Self
A Common Data Representation (CDR)-encoded data.
Constant alias for string: “application/cdr
- APPLICATION_COAP_PAYLOAD: Self
Constrained Application Protocol (CoAP) data intended for CoAP-to-HTTP and HTTP-to-CoAP proxies.
Constant alias for string: “application/coap-payload”.
- APPLICATION_JAVA_SERIALIZED_OBJECT: Self
A Java serialized object.
Constant alias for string: “application/java-serialized-object”.
- APPLICATION_JSON: Self
JSON data intended to be consumed by an application.
Constant alias for string: “application/json”.
- APPLICATION_JSONPATH: Self
A JSONPath defines a string syntax for selecting and extracting JSON values from within a given JSON value.
Constant alias for string: “application/jsonpath”.
- APPLICATION_JSON_PATCH_JSON: Self
Defines a JSON document structure for expressing a sequence of operations to apply to a JSON document.
Constant alias for string: “application/json-patch+json”.
- APPLICATION_JSON_SEQ: Self
A JSON text sequence consists of any number of JSON texts, all encoded in UTF-8.
Constant alias for string: “application/json-seq”.
- APPLICATION_JWT: Self
A JSON Web Token (JWT).
Constant alias for string: “application/jwt”.
- APPLICATION_MP4: Self
An application-specific MPEG-4 encoded data, either audio or video.
Constant alias for string: “application/mp4”.
- APPLICATION_OCTET_STREAM: Self
An application-specific stream of bytes.
Constant alias for string: “application/octet-stream”.
- APPLICATION_OPENMETRICS_TEXT: Self
An openmetrics text data representation, commonly used by Prometheus.
Constant alias for string: “application/openmetrics-text”.
- APPLICATION_PROTOBUF: Self
An application-specific protobuf-encoded data.
Constant alias for string: “application/protobuf”.
- APPLICATION_PYTHON_SERIALIZED_OBJECT: Self
A Python object serialized using pickle.
Constant alias for string: “application/python-serialized-object”.
- APPLICATION_SOAP_XML: Self
A SOAP 1.2 message serialized as XML 1.0.
Constant alias for string: “application/soap+xml”.
- APPLICATION_SQL: Self
An application-specific SQL query.
Constant alias for string: “application/sql”.
- APPLICATION_XML: Self
An XML file intended to be consumed by an application.
Constant alias for string: “application/xml”.
- APPLICATION_X_WWW_FORM_URLENCODED: Self
An encoded a list of tuples, each consisting of a name and a value.
Constant alias for string: “application/x-www-form-urlencoded”.
- APPLICATION_YAML: Self
YAML data intended to be consumed by an application.
Constant alias for string: “application/yaml”.
- APPLICATION_YANG: Self
A YANG-encoded data commonly used by the Network Configuration Protocol (NETCONF).
Constant alias for string: “application/yang”.
- AUDIO_AAC: Self
A MPEG-4 Advanced Audio Coding (AAC) media.
Constant alias for string: “audio/aac”.
- AUDIO_FLAC: Self
A Free Lossless Audio Codec (FLAC) media.
Constant alias for string: “audio/flac”.
- AUDIO_MP4: Self
An audio codec defined in MPEG-1, MPEG-2, MPEG-4, or registered at the MP4 registration authority.
Constant alias for string: “audio/mp4”.
- AUDIO_OGG: Self
An Ogg-encapsulated audio stream.
Constant alias for string: “audio/ogg”.
- AUDIO_VORBIS: Self
A Vorbis-encoded audio stream.
Constant alias for string: “audio/vorbis”.
- IMAGE_BMP: Self
A BitMap (BMP) image.
Constant alias for string: “image/bmp”.
- IMAGE_GIF: Self
A Graphics Interchange Format (GIF) image.
Constant alias for string: “image/gif”.
- IMAGE_JPEG: Self
A Joint Photographic Experts Group (JPEG) image.
Constant alias for string: “image/jpeg”.
- IMAGE_PNG: Self
A Portable Network Graphics (PNG) image.
Constant alias for string: “image/png”.
- IMAGE_WEBP: Self
A Web Protable (WebP) image.
Constant alias for string: “image/webp
- TEXT_CSS: Self
A CSS file.
Constant alias for string: “text/css”.
- TEXT_CSV: Self
A CSV file.
Constant alias for string: “text/csv”.
- TEXT_HTML: Self
An HTML file.
Constant alias for string: “text/html”.
- TEXT_JAVASCRIPT: Self
A JavaScript file.
Constant alias for string: “text/javascript”.
- TEXT_JSON: Self
JSON data intended to be human readable.
Constant alias for string: “text/json”.
- TEXT_JSON5: Self
JSON5 encoded data intended to be human readable.
Constant alias for string: “text/json5”.
- TEXT_MARKDOWN: Self
A MarkDown file.
Constant alias for string: “text/markdown”.
- TEXT_PLAIN: Self
A textual file.
Constant alias for string: “text/plain”.
- TEXT_XML: Self
An XML file that is human readable.
Constant alias for string: “text/xml”.
- TEXT_YAML: Self
YAML data intended to be human readable.
Constant alias for string: “text/yaml”.
- VIDEO_H261: Self
An h261-encoded video stream.
Constant alias for string: “video/h261”.
- VIDEO_H263: Self
An h263-encoded video stream.
Constant alias for string: “video/h263”.
- VIDEO_H264: Self
An h264-encoded video stream.
Constant alias for string: “video/h264”.
- VIDEO_H265: Self
An h265-encoded video stream.
Constant alias for string: “video/h265”.
- VIDEO_H266: Self
An h266-encoded video stream.
Constant alias for string: “video/h266”.
- VIDEO_MP4: Self
A video codec defined in MPEG-1, MPEG-2, MPEG-4, or registered at the MP4 registration authority.
Constant alias for string: “video/mp4”.
- VIDEO_OGG: Self
An Ogg-encapsulated video stream.
Constant alias for string: “video/ogg”.
- VIDEO_RAW: Self
An uncompressed, studio-quality video stream.
Constant alias for string: “video/raw”.
- VIDEO_VP8: Self
A VP8-encoded video stream.
Constant alias for string: “video/vp8”.
- VIDEO_VP9: Self
A VP9-encoded video stream.
Constant alias for string: “video/vp9”.
- ZENOH_BYTES: Self
Just some bytes.
Constant alias for string: “zenoh/bytes”.
- ZENOH_SERIALIZED: Self
Zenoh serialized data.
Constant alias for string: “zenoh/serialized”.
- ZENOH_STRING: Self
A UTF-8 string.
Constant alias for string: “zenoh/string”.
- final class zenoh.EntityGlobalId
The ID globally identifying an entity in a zenoh system.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property eid: int
Returns the EntityId used to identify the entity in a Zenoh session.
- final class zenoh.Hello
A zenoh Hello message.
A Hello message is returned in the ::ref::scouting process for each found Zenoh node on the network. It contains information about the node’s identity and its addresses in locators format.
- property locators: list[str]
Get the locators (network addresses) of the Zenoh node.
- final class zenoh.KeyExpr(key_expr)
Key expressions are Zenoh’s address space for data routing and selection.
A KeyExpr represents a set of keys in a hierarchical namespace using slash-separated paths with wildcard support (
*and**). It may carry optimizations for use with a Session that has declared it.For detailed information about key expressions, see Key Expressions.
- Parameters:
key_expr (str) –
- Return type:
Self
- classmethod autocanonize(key_expr)
Canonizes the passed value before returning it as a KeyExpr. Raises
ZErrorif the passed value isn’t a valid key expression despite canonization.- Parameters:
key_expr (str) –
- Return type:
Self
- concat(other)
Performs string concatenation and returns the result as a KeyExpr. Raises
ZErrorif the result is not a valid key expression. You should probably preferjoin()as Zenoh may then take advantage of the hierachical separation it inserts.- Parameters:
other (str) –
- Return type:
- includes(other)
Returns true if self includes other, i.e. the set defined by self contains every key belonging to the set defined by other.
- Parameters:
other (KeyExpr | str) –
- Return type:
bool
- intersects(other)
Returns true if the keyexprs intersect, i.e. there exists at least one key which is contained in both of the sets defined by self and other.
- Parameters:
other (KeyExpr | str) –
- Return type:
bool
- join(other)
Joins both sides, inserting a / in between them. This should be your prefered method when concatenating path segments.
- Parameters:
other (str) –
- Return type:
- relation_to(other)
- Returns the relation between self and other from self’s point of view (
SetIntersectionLevel.INCLUDESsignifies that self includes other). Note that this is slower than
intersects()andincludes(), so you should favor these methods for most applications.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
other (KeyExpr | str) –
- Return type:
- Returns the relation between self and other from self’s point of view (
- final class zenoh.Liveliness
A structure with functions to declare a
LivelinessToken, query existingLivelinessTokens and subscribe to liveliness changes.A
LivelinessTokenis a token whose liveliness is tied to the ZenohSessionand can be monitored by remote applications.The Liveliness structure can be obtained with the
Session.liveliness()method of theSessionclass.For more information, see Liveliness.
- declare_subscriber(key_expr, handler=None, *, history=None)
Create a
Subscriberfor liveliness changes matching the given key expression.- Parameters:
key_expr (KeyExpr | str) – The
LivelinessTokenkey expression.handler (DefaultHandler[Sample] | FifoChannel[Sample] | RingChannel[Sample] | tuple[Callable[[Sample], Any], Any] | Callable[[Sample], Any] | None) – The handler for receiving liveliness samples (see Channels and callbacks).
history (bool | None) – If True, the already present liveliness tokens will be reported upon declaration.
- Return type:
- declare_token(key_expr)
Create a
LivelinessTokenfor the given key expression.- Parameters:
key_expr (KeyExpr | str) –
- Return type:
- get(key_expr, handler=None, *, timeout=None, cancellation_token=None)
Query
LivelinessTokenwith matching key expressions.- Parameters:
key_expr (KeyExpr | str) –
handler (DefaultHandler[Reply] | FifoChannel[Reply] | RingChannel[Reply] | tuple[Callable[[Reply], Any], Any] | Callable[[Reply], Any] | None) –
timeout (float | int | None) –
cancellation_token (CancellationToken | None) –
- Return type:
- final class zenoh.LivelinessToken
A token whose liveliness is tied to the Zenoh
Sessionand can be monitored by remote applications using theLivelinessstructure. The token is declared usingLiveliness.declare_token()with a specific key expression.- undeclare()
Undeclare the
LivelinessToken.
- final enum zenoh.Locality(value)
The locality of samples/queries to be received by subscribers/queryables or targeted by publishers/queriers.
This enum controls whether data is exchanged only with local entities (in the same session), only with remote entities, or with both. It is used in the following settings:
Session.declare_subscriber()(allowed_origin)Session.declare_queryable()(allowed_origin)Session.declare_publisher()(allowed_destination)Session.declare_querier()(allowed_destination)
Valid values are as follows:
- SESSION_LOCAL = <Locality.SESSION_LOCAL: 1>
Request/serve data only to entities in the same session.
- REMOTE = <Locality.REMOTE: 2>
Request/serve data only to remote entities (not in the same session).
- ANY = <Locality.ANY: 3>
Request/serve data to both local and remote entities.
- final class zenoh.MatchingListener
A listener that sends notifications when the
MatchingStatusof a corresponding Zenoh entity changes.The matching listener allows publishers and queriers to detect when there are matching subscribers or queryables on the network, enabling efficient resource usage.
See also: Matching
- recv()
- Parameters:
self (MatchingListener[Handler[MatchingStatus]]) –
- Return type:
- try_recv()
- Parameters:
self (MatchingListener[Handler[MatchingStatus]]) –
- Return type:
MatchingStatus | None
- undeclare()
Close a Matching listener. Matching listeners are automatically closed when dropped, but you may want to use this function to handle errors or close the Matching listener asynchronously.
- property handler: _H
The handler associated with this MatchingListener instance.
See Channels and callbacks for more information on handlers.
- final class zenoh.MatchingStatus
A struct that indicates if there exist entities matching the key expression.
See also: Matching
- property matching: bool
Return true if there exist entities matching the target (i.e either Subscribers matching Publisher’s key expression or Queryables matching Querier’s key expression and target).
- final class zenoh.NTP64(seconds, nanos)
A NTP 64-bits format as specified in RFC-5909 <https://tools.ietf.org/html/rfc5905#section-6>
The 1st 32-bits part is the number of second since the EPOCH of the physical clock, and the 2nd 32-bits part is the fraction of second.
- Parameters:
seconds (int) –
nanos (int) –
- Return type:
Self
- as_nanos()
Returns the total duration converted to nanoseconds.
- Return type:
int
- as_secs()
Returns the 32-bits seconds part.
- Return type:
int
- as_secs_f64()
Returns this NTP64 as a f64 in seconds.
The integer part of the f64 is the NTP64’s Seconds part. The decimal part of the f64 is the result of a division of NTP64’s Fraction part divided by 2^32. Considering the probable large number of Seconds (for a time relative to UNIX_EPOCH), the precision of the resulting f64 might be in the order of microseconds. Therefore, it should not be used for comparison. Directly comparing [NTP64] objects is preferable.
- Return type:
float
- classmethod parse_rfc3339(s)
Parse a RFC3339 time representation into a NTP64.
- Parameters:
s (str) –
- Return type:
Self
- subsec_nanos()
Returns the 32-bits fraction of second part converted to nanoseconds.
- Return type:
int
- to_datetime()
Returns this NTP64 as a datetime.
- Return type:
datetime
- to_string_rfc3339_lossy()
Convert to a RFC3339 time representation with nanoseconds precision.
e.g.: “2024-07-01T13:51:12.129693000Z”`
- Return type:
str
- final class zenoh.Parameters(parameters=None)
A collection of key-value parameters used in query operations.
Parameters allow attaching additional metadata to queries. They can be constructed from dictionaries, strings, or built programmatically. When combined with a key expression, they form a
Selectorfor query operations.See also: Query Parameters
- Parameters:
parameters (dict[str, str] | str | None) –
- extend(parameters)
Extend these properties with other properties.
- Parameters:
parameters (Parameters | dict[str, str] | str) –
- get(key, default=None)
Returns the value corresponding to the key.
- Parameters:
key (str) –
default (str | None) –
- Return type:
str | None
- insert(key, value)
Inserts a key-value pair into the map. If the map did not have this key present, None` is returned. If the map did have this key present, the value is updated, and the old value is returned.
- Parameters:
key (str) –
value (str) –
- is_empty()
Returns true if properties does not contain anything.
- Return type:
bool
- is_ordered()
Returns true if all keys are sorted in alphabetical order.
- Return type:
bool
- remove(key)
Removes a key from the map, returning the value at the key if the key was previously in the properties.
- Parameters:
key (str) –
- values(key)
Returns the list of values corresponding to the key.
- Parameters:
key (str) –
- Return type:
list[str]
- final enum zenoh.Priority(value)
The priority of Zenoh messages.
Priority determines the transmission priority of messages, with higher priority messages being delivered before lower priority ones when network congestion occurs.
See also: https://docs.rs/zenoh/latest/zenoh/qos/enum.Priority.html
Valid values are as follows:
- REAL_TIME = <Priority.REAL_TIME: 1>
- INTERACTIVE_HIGH = <Priority.INTERACTIVE_HIGH: 2>
- INTERACTIVE_LOW = <Priority.INTERACTIVE_LOW: 3>
- DATA_HIGH = <Priority.DATA_HIGH: 4>
- DATA = <Priority.DATA: 5>
- DATA_LOW = <Priority.DATA_LOW: 6>
- BACKGROUND = <Priority.BACKGROUND: 7>
- final class zenoh.Publisher
A publisher that allows sending data through a stream.
Publishers are automatically undeclared when dropped.
A publisher is created using
zenoh.Session.declare_publisher()and is used to publish data toSubscriberinstances matching the publisher’s key expression.Publishers can declare
MatchingListenerinstances to monitor if subscribers matching the publisher’s key expression are present in the network.For more information about publish/subscribe operations, see Publish/Subscribe.
- declare_matching_listener(handler=None)
Create a
MatchingListener. It will send notifications each time the matching status of this publisher changes.- Parameters:
handler (DefaultHandler[MatchingStatus] | FifoChannel[MatchingStatus] | RingChannel[MatchingStatus] | tuple[Callable[[MatchingStatus], Any], Any] | Callable[[MatchingStatus], Any] | None) –
- Return type:
- delete(*, attachment=None, timestamp=None, source_info=None)
Declare that data associated with this publisher’s key expression is deleted.
Subscriberinstances will receive azenoh.Samplewithzenoh.SampleKind.DELETEkind, indicating that the data is no longer associated with the key expression.- Parameters:
attachment (Any | None) –
timestamp (Timestamp | None) –
source_info (SourceInfo | None) –
- put(payload, *, encoding=None, attachment=None, timestamp=None, source_info=None)
Publish data to
Subscriberinstances matching this publisher’s key expression.Subscribers will receive the data as a
zenoh.Samplewithzenoh.SampleKind.PUTkind.- Parameters:
payload (Any) –
encoding (Encoding | str | None) –
attachment (Any | None) –
timestamp (Timestamp | None) –
source_info (SourceInfo | None) –
- undeclare()
Undeclare the publisher, informing the network that it needn’t optimize publications for its key expression anymore.
- property congestion_control: CongestionControl
The congestion control strategy applied when routing data.
- property id: EntityGlobalId
The global ID of this publisher. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property matching_status: bool
Whether there are subscribers matching this publisher’s key expression.
- property reliability: Reliability
The reliability applied when routing data. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final class zenoh.Querier
A querier that allows sending queries to a
Queryable.The querier is a preconfigured object that can be used to send multiple queries to a given key expression. It is declared using
Session.declare_querier(). Queriers are automatically undeclared when dropped.See Query/Reply for more information on the query/reply paradigm.
- declare_matching_listener(handler=None)
Returns a
MatchingListenerfor this Querier.The
MatchingListenerwill send a notification each time theMatchingStatusof the Querier changes.- Parameters:
handler (DefaultHandler[MatchingStatus] | FifoChannel[MatchingStatus] | RingChannel[MatchingStatus] | tuple[Callable[[MatchingStatus], Any], Any] | Callable[[MatchingStatus], Any] | None) –
- Return type:
- get(handler=None, *, parameters=None, payload=None, encoding=None, attachment=None, source_info=None, cancellation_token=None)
Sends a query and returns a channel for processing replies.
See Channels and callbacks for more information on handlers.
- Parameters:
handler (DefaultHandler[Reply] | FifoChannel[Reply] | RingChannel[Reply] | tuple[Callable[[Reply], Any], Any] | Callable[[Reply], Any] | None) –
parameters (Parameters | dict[str, str] | str | None) –
payload (Any | None) –
encoding (Encoding | str | None) –
attachment (Any | None) –
source_info (SourceInfo | None) –
cancellation_token (CancellationToken | None) –
- Return type:
- undeclare()
Undeclares the Querier, informing the network that it needn’t optimize queries for its key expression anymore.
- property accept_replies: ReplyKeyExpr
Returns the
ReplyKeyExprsetting of this querier.
- property id: EntityGlobalId
Returns the
EntityGlobalIdof this Querier. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final class zenoh.Query
A request received by a
Queryable.It contains the key expression, parameters, payload, and attachment sent by a querier via
Session.get()orQuerier.get(). Use its methods to send replies.Note
The Query’s
key_expris not the key expression which should be used as the parameter ofreply(), because it may contain globs. TheQueryable’s key expression is the one that should be used.This parameter is not set automatically because
Queryableitself may serve glob key expressions and send replies on different concrete key expressions matching this glob. For example, aQueryableservingfoo/*may receive aQuerywith key expressionfoo/barand another one withfoo/baz, and it should reply respectively onfoo/barandfoo/baz.Note
By default, queries only accept replies whose key expression intersects with the query’s. I.e. it’s not possible to send reply with key expression
foo/barto a query with key expressionbaz/*. To allow disjoint replies, use theaccept_repliesparameter withReplyKeyExpr.ANYinSession.get()orSession.declare_querier(). Alternatively, the query may contain special parameter_anykewhich also enables disjoint replies. See theSelectordocumentation for more information about this parameter.See Query/Reply for more information on the query/reply paradigm.
- accepts_replies()
Returns the
ReplyKeyExprsetting of this query, indicating whether replies must match the query’s key expression or can use any key expression.- Return type:
- drop()
Drop the instance of a query. The query will only be finalized when all query instances (one per queryable matched) are dropped. Finalization is required to not have query hanging on the querier side.
This method should be called after handling the query, as Python finalizers are not reliable, especially when it comes to loop variables. It is also possible, and advised, to use query context manager, which calls drop on exit. Once a query is dropped, it’s no more possible to use it, and its methods will raise an exception.
- reply(key_expr, payload, *, encoding=None, congestion_control=None, priority=None, express=None, attachment=None, timestamp=None)
Sends a
Sampleof kindSampleKind.PUTas a reply to this query.Note
See the class documentation for important details about which key expression to use for replies.
Deprecated since version The:
congestion_controlandpriorityparameters are deprecated and will be ignored. Response QoS now automatically matches the original query’s QoS to avoid priority inversion.- Parameters:
key_expr (KeyExpr | str) –
payload (Any) –
encoding (Encoding | str | None) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
attachment (Any | None) –
timestamp (Timestamp | None) –
- reply_del(key_expr, *, congestion_control=None, priority=None, express=None, attachment=None, timestamp=None)
Sends a
Sampleof kindSampleKind.DELETEas a reply to this query.By default, queries only accept replies whose key expression intersects with the query’s. Unless the query has enabled disjoint replies (you can check this through
accepts_replies()), replying on a disjoint key expression will result in an error when resolving the reply.Note
See the class documentation for important details about which key expression to use for replies.
Deprecated since version The:
congestion_controlandpriorityparameters are deprecated and will be ignored. Response QoS now automatically matches the original query’s QoS to avoid priority inversion.- Parameters:
key_expr (KeyExpr | str) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
attachment (Any | None) –
timestamp (Timestamp | None) –
- reply_err(payload, *, encoding=None)
Sends a
ReplyErroras a reply to this query.- Parameters:
payload (Any) –
encoding (Encoding | str | None) –
- property parameters: Parameters
The selector parameters of this query.
- property source_info: SourceInfo | None
Gets info on the source of this Query. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final class zenoh.QueryConsolidation(mode, /)
The reply consolidation strategy to apply to replies to a get.
By default, the consolidation strategy is
QueryConsolidation.AUTO, which lets the implementation choose the best strategy depending on the query parameters and the number of responders. Other strategies can be selected by using a specificConsolidationModeas a parameter of theSession.declare_querier()orSession.get()methods.See the documentation of
ConsolidationModefor more details about each strategy.- Parameters:
mode (ConsolidationMode) –
- Return type:
Self
- AUTO: Self
- DEFAULT: Self
- property mode: ConsolidationMode
- final enum zenoh.QueryTarget(value)
The Queryables to which a query from
Session.get()orSession.declare_querier()is delivered.QueryTarget.ALLmakes the query be delivered to all the matching queryables.QueryTarget.ALL_COMPLETEmakes the query be delivered to all the matching queryables which are marked as “complete”.QueryTarget.BEST_MATCHING(default) makes the data to be requested from the queryable(s) selected by zenoh to get the fastest and most complete reply.It is set by the target parameter of
Session.get()orSession.declare_querier()methods.Valid values are as follows:
- BEST_MATCHING = <QueryTarget.BEST_MATCHING: 1>
Let Zenoh find the best matching queryable capable of serving the query.
- ALL = <QueryTarget.ALL: 2>
Deliver the query to all queryables matching the query’s key expression.
- ALL_COMPLETE = <QueryTarget.ALL_COMPLETE: 3>
Deliver the query to all queryables matching the query’s key expression that are declared as complete.
- final class zenoh.Queryable
A Queryable is an entity that implements Query/Reply pattern.
It is declared by the
Session.declare_queryable()method and providesQuery`es using callback or channel. The Queryable receives :class:`Queryrequests fromQuerier.get()orSession.get()and sends back replies with the methods ofQuery.reply(),Query.reply_err(), orQuery.reply_del().- undeclare()
Undeclare the Queryable.
- property handler: _H
The handler associated with this Queryable instance.
See Channels and callbacks for more information on handlers.
- property id: EntityGlobalId
Returns the
EntityGlobalIdof this Queryable. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final enum zenoh.Reliability(value)
Reliability guarantees for message delivery.
Used when declaring publishers with
Session.declare_publisher()and accessible via thePublisher.reliabilityproperty.Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
Valid values are as follows:
- BEST_EFFORT = <Reliability.BEST_EFFORT: 1>
Messages may be lost.
- RELIABLE = <Reliability.RELIABLE: 2>
Messages are guaranteed to be delivered.
- final class zenoh.Reply
An answer received from a
Queryable.Contains the result of a request to a
QueryablebySession.get()orQuerier.get(). May be either a successful result with aSampleor an error with aReplyError.- property err: ReplyError | None
Returns the error if this reply failed, None otherwise.
- property ok: Sample | None
Returns the successful result if this reply is successful, None otherwise.
- property replier_id: EntityGlobalId | None
Returns the ID of the zenoh instance that answered this reply. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property result: Sample | ReplyError
Gets the result of this reply which may be either a successful
Sampleor an errorReplyError.
- final class zenoh.ReplyError
An error reply received from a
Queryableand available in theReplystructure.
- final enum zenoh.ReplyKeyExpr(value)
Controls whether replies to a query must match the query’s key expression.
ReplyKeyExpr.MATCHING_QUERY(default) means that replies must have a key expression matching the query’s key expression.ReplyKeyExpr.ANYallows replies with any key expression, even if it doesn’t match the query.It is set by the
accept_repliesparameter ofSession.get()orSession.declare_querier()methods.Valid values are as follows:
- ANY = <ReplyKeyExpr.ANY: 1>
Accept replies whose key expressions may not match the query key expression.
- MATCHING_QUERY = <ReplyKeyExpr.MATCHING_QUERY: 2>
Accept replies whose key expressions match the query key expression.
- final class zenoh.Sample
The Sample structure is the data unit received by
Subscriber, or byQuerierorSession.get()as part of theReply.It contains the payload and all metadata associated with the data.
- property congestion_control: CongestionControl
Gets the congestion control of this Sample.
- property express: bool
Gets the express flag value.
If true, the message is not batched during transmission, in order to reduce latency.
- property kind: SampleKind
Gets the kind of this Sample.
- property source_info: SourceInfo | None
Gets info on the source of this Sample. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final enum zenoh.SampleKind(value)
The kind of a
Sample, indicating whether it contains data or indicates deletion.Valid values are as follows:
- PUT = <SampleKind.PUT: 1>
A PUT sample containing data.
- DELETE = <SampleKind.DELETE: 2>
A DELETE sample indicating data removal.
- final class zenoh.Scout
A Scout object that yields
zenoh.Hellomessages for discovered Zenoh nodes on the network.Scout is returned by the
zenoh.scout()function and is used to discover Zenoh nodes (routers and peers) on the network. It yieldszenoh.Hellomessages containing information about each discovered node.See Scouting for more details on the scouting process.
- recv()
Receive a
zenoh.Hellomessage, blocking until one is available.
- stop()
Stop the scouting process.
- try_recv()
Try to receive a
zenoh.Hellomessage without blocking. Returns None if no message is available.
- property handler: _H
The handler associated with this Scout instance.
See Channels and callbacks for more information on handlers.
- final class zenoh.Selector(arg, /, parameters=None)
A selector is the combination of a
KeyExpr, which defines the set of keys that are relevant to an operation, and a set ofParameterswith a few intended uses.Creating a Selector
A
Selectorcan be created from a key expression and optional parameters:selector = zenoh.Selector("key/expression", parameters)
Or from a complete selector string:
selector = zenoh.Selector("key/expression?param1=value1;param2=value2")
If first parameter is already a complete selector string, the parameters should be omitted.
A selector is the combination of a
KeyExpr, which defines the set of keys that are relevant to an operation, and a set ofParameterswith a few intended uses:specifying arguments to a
Queryable, allowing the passing of Remote Procedure Call parametersfiltering by value
filtering by metadata, such as the timestamp of a value
specifying arguments to zenoh when using the REST API
When in string form, selectors look a lot like a URI, with similar semantics:
the
key_exprbefore the first?must be a valid key expression.the
parametersafter the first?should be encoded like the query section of a URL:parameters are separated by
;the parameter name and value are separated by the first
=in the absence of
=, the parameter value is considered to be the empty stringboth name and value should use percent-encoding (URL-encoding) to escape characters
defining a value for the same parameter name twice is considered undefined behavior, with the encouraged behaviour being to reject operations when a duplicate parameter is detected
Zenoh intends to standardize the usage of a set of parameter names. To avoid conflicting with RPC parameters, the Zenoh team has settled on reserving the set of parameter names that start with non-alphanumeric characters.
Queryableimplementers are encouraged to prefer these standardized parameter names when implementing their associated features, and to prefix their own parameter names to avoid having conflicting parameter names with other queryables.Here are the currently standardized parameters for Zenoh (check the specification page, for the exhaustive list):
[unstable]_time: used to express interest in only values dated within a certain time range, values for this parameter must be readable by the Zenoh Time DSL for the value to be considered valid._anyke: used in queries to express interest in replies coming from any key expression. By default, only replies whose key expression match query’s key expression are accepted._anykedisables the query-reply key expression matching check. See alsoReplyKeyExpr.ANYas the preferred API for this functionality.
See also: Key Expressions, Query Parameters
- Parameters:
arg (_IntoKeyExpr | str) –
parameters (_IntoParameters | None) –
- property parameters: Parameters
The parameters part of this selector.
- final class zenoh.Session
The Session is the main component of Zenoh. It holds the zenoh runtime object, which maintains the state of the connection of the node to the Zenoh network.
The session allows declaring other zenoh entities like
Publisher,Subscriber,Querier,Queryable, and obtainingLivelinessinstances, and keeps them functioning. Closing the session will undeclare all objects declared by it.A Zenoh session is instantiated using
open()with parameters specified in theConfigobject.- close()
Close the zenoh Session.
Every
SubscriberandQueryabledeclared will stop receiving data, and further attempts to publish or query will result in an error. Undeclaring an entity after session closing is a no-op. Session state can be checked withis_closed().Sessions are automatically closed when all their instances are dropped. But it can be useful to close the session explicitly.
- declare_keyexpr(key_expr)
Informs Zenoh that you intend to use the provided key_expr multiple times and that it should optimize its transmission.
- Parameters:
key_expr (KeyExpr | str) –
- declare_publisher(key_expr, *, encoding=None, congestion_control=None, priority=None, express=None, reliability=None, allowed_destination=None)
Create a
Publisherfor the given key expression.- Parameters:
key_expr (KeyExpr | str) –
encoding (Encoding | str | None) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
reliability (Reliability | None) –
allowed_destination (Locality | None) –
- Return type:
- declare_querier(key_expr, *, target=None, consolidation=None, accept_replies=None, timeout=None, congestion_control=None, priority=None, express=None, allowed_destination=None)
Create a
Querierfor the given key expression.- Parameters:
key_expr (KeyExpr | str) –
target (QueryTarget | None) –
consolidation (ConsolidationMode | None) –
accept_replies (ReplyKeyExpr | None) –
timeout (float | int | None) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
allowed_destination (Locality | None) –
- Return type:
- declare_queryable(key_expr, handler=None, *, complete=None, allowed_origin=None)
Create a
Queryablefor the given key expression.- Parameters:
key_expr (KeyExpr | str) –
handler (DefaultHandler[Query] | FifoChannel[Query] | RingChannel[Query] | tuple[Callable[[Query], Any], Any] | Callable[[Query], Any] | None) –
complete (bool | None) –
allowed_origin (Locality | None) –
- Return type:
- declare_subscriber(key_expr, handler=None, *, allowed_origin=None)
Create a
Subscriberfor the given key expression.- Parameters:
key_expr (KeyExpr | str) –
handler (DefaultHandler[Sample] | FifoChannel[Sample] | RingChannel[Sample] | tuple[Callable[[Sample], Any], Any] | Callable[[Sample], Any] | None) –
allowed_origin (Locality | None) –
- Return type:
- delete(key_expr, *, congestion_control=None, priority=None, express=None, attachment=None, timestamp=None, allowed_destination=None, source_info=None)
Publish a delete sample directly from the session.
This is a shortcut for declaring a
Publisherand calling delete on it.- Parameters:
key_expr (KeyExpr | str) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
attachment (Any | None) –
timestamp (Timestamp | None) –
allowed_destination (Locality | None) –
source_info (SourceInfo | None) –
- get(selector, handler=None, *, target=None, consolidation=None, accept_replies=None, timeout=None, congestion_control=None, priority=None, express=None, payload=None, encoding=None, attachment=None, allowed_destination=None, source_info=None, cancellation_token=None)
Query data from the matching queryables in the system.
This is a shortcut for declaring a
Querierand calling get on it.- Parameters:
handler (DefaultHandler[Reply] | FifoChannel[Reply] | RingChannel[Reply] | tuple[Callable[[Reply], Any], Any] | Callable[[Reply], Any] | None) –
target (QueryTarget | None) –
consolidation (ConsolidationMode | None) –
accept_replies (ReplyKeyExpr | None) –
timeout (float | int | None) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
payload (Any) –
encoding (Encoding | str | None) –
attachment (Any | None) –
allowed_destination (Locality | None) –
source_info (SourceInfo | None) –
cancellation_token (CancellationToken | None) –
- Return type:
- is_closed()
Check if the session has been closed.
- Return type:
bool
- liveliness()
Obtain a
Livelinessinstance tied to this Zenoh session.- Return type:
- new_timestamp()
Get a new
Timestampfrom a Zenoh session.The returned timestamp has the current time, with the session’s runtime
ZenohIdas the unique identifier. This ensures that timestamps from different sessions are unique even when created at the same time.- Returns:
A new
Timestampwith current time and session’s unique ID.
- Return type:
- put(key_expr, payload, *, encoding=None, congestion_control=None, priority=None, express=None, attachment=None, timestamp=None, allowed_destination=None, source_info=None)
Publish data directly from the session.
This is a shortcut for declaring a
Publisherand calling put on it.- Parameters:
key_expr (KeyExpr | str) –
payload (Any) –
encoding (Encoding | str | None) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
attachment (Any | None) –
timestamp (Timestamp | None) –
allowed_destination (Locality | None) –
source_info (SourceInfo | None) –
- property id: EntityGlobalId
Returns the global identifier of the session object. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property info: SessionInfo
Get information about the session: the session id, the connected nodes.
- final class zenoh.SessionInfo
Struct returned by
Session.info()that allows access to information about the current zenohSession.This information includes the
ZenohIdidentifier of the current session, and the identifiers of the connected routers and peers (see alsoWhatAmIfor more information about peers and routers).- peers_zid()
Return the
ZenohIdof the zenoh peers this process is currently connected to.- Return type:
list[ZenohId]
- final enum zenoh.SetIntersectionLevel(value)
The possible relations between two sets of key expressions defined by glob patterns.
Each glob key expression defines a set of possible concrete key expressions that it matches. This enum describes how two such sets relate to each other.
Returned by
KeyExpr.relation_to().Note that
EQUALSimpliesINCLUDES, which itself impliesINTERSECTS.You can check for intersection with level >= SetIntersectionLevel.INTERSECTS and for inclusion with level >= SetIntersectionLevel.INCLUDES.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
Valid values are as follows:
- DISJOINT = <SetIntersectionLevel.DISJOINT: 1>
The sets have no key expressions in common. Example:
foo/*andbar/*- no overlap.
- INTERSECTS = <SetIntersectionLevel.INTERSECTS: 2>
The sets have some key expressions in common, but neither fully contains the other. Example:
foo/*and*/bar-foo/barmatches both.
- INCLUDES = <SetIntersectionLevel.INCLUDES: 3>
The first set fully contains the second set. Example:
foo/**includesfoo/*(where**matches any number of sections).
- EQUALS = <SetIntersectionLevel.EQUALS: 4>
The sets are identical. Example:
foo/*andfoo/*.
- final class zenoh.SourceInfo(source_id, source_sn)
Information on the source of a zenoh Sample.
Contains metadata about the origin of a data sample, including the source entity’s global identifier and sequence number.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
source_id (EntityGlobalId) –
source_sn (SourceSn) –
- Return type:
Self
- property source_id: EntityGlobalId
The EntityGlobalId of the zenoh entity that published the Sample in question.
- property source_sn: int
The sequence number of the Sample from the source.
- final class zenoh.Subscriber
A subscriber that receives data from
Publisherinstances matching its key expression.Subscribers are automatically undeclared when dropped.
A subscriber is created using
zenoh.Session.declare_subscriber()and is used to receive data fromPublisherinstances matching the subscriber’s key expression.For more information about publish/subscribe operations, see Publish/Subscribe.
- recv()
Receive a
Sample, blocking until one is available.- Parameters:
self (Subscriber[Handler[Sample]]) –
- Return type:
- try_recv()
Try to receive a
Samplewithout blocking.Returns the sample if available, or None if no sample is ready.
- Parameters:
self (Subscriber[Handler[Sample]]) –
- Return type:
Sample | None
- undeclare()
Close a Subscriber. Subscribers are automatically closed when dropped, but you may want to use this function to handle errors or close the Subscriber asynchronously.
- property handler: _H
The handler associated with this Subscriber instance.
See Channels and callbacks for more information on handlers.
- property id: EntityGlobalId
The global ID of this subscriber. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final class zenoh.Timestamp(time, id)
A timestamp consisting of an NTP64 time and a unique identifier.
Timestamps are used to provide temporal ordering and uniqueness in Zenoh operations. They combine a high-precision NTP64 timestamp with a unique identifier to ensure causality and ordering in distributed systems.
Timestamps can be created using
Session.new_timestamp(), which returns a timestamp with the current time and the session’s unique runtime identifier.String Representations:
Timestamps support two string formats:
Default format:
"<ntp64_time>/<id_hex>"(e.g.,"7386690599959157260/33") This is a lossless, machine-readable format.RFC3339 format:
"<rfc3339_time>/<id_hex>"(e.g.,"2024-07-01T13:51:12.129693000Z/33") This is a human-readable format with nanosecond precision, but may lose some precision due to rounding when converting fractional seconds to nanoseconds.
For detailed information about Timestamp, see: https://docs.rs/zenoh/latest/zenoh/time/struct.Timestamp.html
- Parameters:
time (datetime | NTP64) –
id (_IntoTimestampId) –
- Return type:
Self
- get_diff_duration(other)
Returns the duration difference between this timestamp and another.
- Args:
other: The timestamp to compare against.
- Returns:
A timedelta representing the time difference.
- Parameters:
other (Timestamp) –
- Return type:
timedelta
- get_id()
Returns the unique identifier component of the timestamp as a
TimestampId.- Return type:
- get_time()
Returns the time component of the timestamp as a datetime object.
- Return type:
datetime
- get_time_as_ntp64()
Returns the time component of the timestamp as a datetime object.
- Return type:
- classmethod parse_rfc3339(s)
Parse a RFC3339 time representation into a Timestamp.
- Args:
s: A string in RFC3339 format with timestamp ID (e.g., “2024-07-01T13:51:12.129693000Z/33”).
- Returns:
A new Timestamp object.
- Raises:
ZError: If the string cannot be parsed.
- Parameters:
s (str) –
- Return type:
Self
- to_string_rfc3339_lossy()
Convert to a RFC3339 time representation with nanoseconds precision.
This format is human-readable but may lose precision due to rounding when converting fractional seconds to nanoseconds.
- Returns:
A string in RFC3339 format (e.g., “2024-07-01T13:51:12.129693000Z/33”).
- Note:
This conversion is not bijective - converting to string and back may result in a slightly different timestamp due to precision loss.
- Return type:
str
- final class zenoh.TimestampId(bytes)
A unique identifier used in
Timestamp.TimestampId represents a unique identifier that is part of every
Timestamp. It is typically derived from aZenohId(session identifier) to ensure that timestamps from different sessions remain unique even when created simultaneously.The identifier is stored as a fixed-size byte array and provides methods for comparison, hashing, and conversion to/from bytes.
Used in:
Timestamp.__new__()- accepts_IntoTimestampId(bytearray, bytes, or TimestampId)Timestamp.get_id()- returns a TimestampIdSession.new_timestamp()- creates timestamps with session’s ZenohId as TimestampId
- Parameters:
bytes (bytearray | bytes) –
- Return type:
Self
- final enum zenoh.WhatAmI(value)
The type of the node in the Zenoh network.
The zenoh application can work in three different modes: router, peer, and client.
For detailed format information, see: https://docs.rs/zenoh/latest/zenoh/config/enum.WhatAmI.html
Valid values are as follows:
- ROUTER = <WhatAmI.ROUTER: 1>
Router mode: Used to run a zenoh router, which is a node that maintains a predefined zenoh network topology. Unlike peers, routers do not discover other nodes by themselves, but rely on static configuration.
- PEER = <WhatAmI.PEER: 2>
Peer mode: The application searches for other nodes and establishes direct connections with them. This can work using multicast discovery and by getting gossip information from the initial entry points. The peer mode is the default mode.
- CLIENT = <WhatAmI.CLIENT: 3>
Client mode: The application remains connected to a single connection point, which serves as a gateway to the rest of the network. This mode is useful for constrained devices that cannot afford to maintain multiple connections.
- final class zenoh.WhatAmIMatcher(matcher=None)
A helper type that allows matching combinations of WhatAmI values in scouting.
WhatAmIMatcher can be created from a string specification like “peer|router” or “client”, or built programmatically using methods like
router(),peer(), andclient().The
scout()function accepts a WhatAmIMatcher to filter the nodes of the specified types.- Parameters:
matcher (str | None) –
- Return type:
Self
- client()
Adds
WhatAmI.CLIENTto the matcher.- Return type:
Self
- classmethod empty()
Creates an empty matcher that matches no node types.
- Return type:
Self
- is_empty()
Returns True if the matcher matches no node types.
- Return type:
bool
- matches(whatami)
Returns True if the given WhatAmI value matches this matcher.
- Parameters:
whatami (WhatAmI) –
- Return type:
bool
- peer()
Adds
WhatAmI.PEERto the matcher.- Return type:
Self
- router()
Adds
WhatAmI.ROUTERto the matcher.- Return type:
Self
- final class zenoh.ZBytes(bytes=None)
ZBytes represents raw bytes data that can be interpreted as strings or byte arrays.
ZBytes is the fundamental data container in Zenoh for all payload and attachment data. It provides flexible access to the underlying bytes, allowing conversion to strings, byte arrays, or direct byte access.
The Zenoh protocol treats ZBytes as opaque binary data and is completely unaware of its content or structure. This allows users to employ any data representation format of their choice, including JSON, protobuf, flatbuffers, MessagePack, or custom formats.
For convenience, Zenoh provides built-in serialization functions
zenoh.ext.z_serialize()andzenoh.ext.z_deserialize()in thezenoh.extmodule, which support serialization of standard Python types (primitives, lists, dicts, etc.) using Zenoh’s native binary format. However, these are not mandatory - users are encouraged to use any serialization approach that fits their needs.- Parameters:
bytes (bytearray | bytes | str | shm.ZShm | shm.ZShmMut | None) –
- Return type:
Self
- as_shm()
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Return type:
ZShm | None
- to_bytes()
Return the underlying data as bytes.
- Returns:
bytes: The raw byte data contained in this ZBytes instance.
- Return type:
bytes
- to_string()
Return the underlying data as a UTF-8 decoded string.
- Returns:
str: The string representation of the byte data, decoded as UTF-8.
- Raises:
ValueError: If the byte data cannot be decoded as valid UTF-8.
- Return type:
str
- final class zenoh.ZenohId
The global unique id of a zenoh peer.
- zenoh.init_log_from_env_or(level)
Redirect zenoh logs to stdout, according to the RUST_LOG environment variable.
For example, RUST_LOG=debug will set the log level to DEBUG. If RUST_LOG is not set, then logging is set to the provided level.
- Parameters:
level (str) –
- zenoh.open(config)
Open a zenoh
zenoh.Session.For more information about sessions and configuration, see Session and Config.
- zenoh.scout(handler=None, what=None, config=None)
Scout for routers and/or peers.
scout spawns a task that periodically sends scout messages and waits for
zenoh.Helloreplies. The scouting process can be stopped by callingzenoh.Scout.stop()on the returnedzenoh.Scoutobject, or by letting thezenoh.Scoutobject go out of scope (dropping it).- Args:
handler: Optional handler for processing received
zenoh.Hellomessages. what: Optionalzenoh.WhatAmIMatcheror string specifying which node types to scout for (e.g., “peer|router”). If None, scouts for all node types. config: Optionalzenoh.Configfor the scouting session.
For more information about scouting, see Scouting.
- Parameters:
handler (DefaultHandler[Hello] | FifoChannel[Hello] | RingChannel[Hello] | tuple[Callable[[Hello], Any], Any] | Callable[[Hello], Any] | None) –
what (WhatAmIMatcher | str | None) –
config (Config | None) –
- Return type:
- zenoh.try_init_log_from_env()
Redirect zenoh logs to stdout, according to the RUST_LOG environment variable.
For example, RUST_LOG=debug will set the log level to DEBUG. If RUST_LOG is not set, then logging is not enabled.
module zenoh.handlers
- final class zenoh.handlers.Callback(callback, drop=None, *, indirect=True)
A callback handler that invokes a user-defined function for each received item.
The Callback class provides a way to handle asynchronous data reception by calling a user-provided callback function for each item received. It can also optionally call a drop function when the associated Zenoh primitive (
zenoh.Subscriber,zenoh.Querier, etc.) is undeclared.When a Callback handler is used, the associated Zenoh primitive runs in background mode, meaning the callback continues to execute even if the object goes out of scope. For more information about channels and callbacks, see Channels and callbacks.
- Args:
- callback:
A callable that will be invoked for each received item.
- drop:
An optional callable that will be invoked when the associated Zenoh primitive is undeclared and the callback handler is being cleaned up.
- indirect:
This feature is unstable and may change or be removed in future releases.
Controls the threading behavior of callback execution. If True (default), the callback is executed in a separate Python thread. If False, the callback is executed directly in the same thread that receives the data (the zenoh network thread).
- Parameters:
callback (Callable[[_T], Any]) –
drop (Callable[[], Any] | None) –
indirect (bool) –
- Return type:
Self
- property callback: Callable[[_T], Any]
The callback function that will be invoked for each received item.
- property drop: Callable[[], Any] | None
The optional drop function that will be invoked when the handler is cleaned up.
- property indirect: bool
Unstable Whether the callback executes in a separate thread (True) or same thread (False).
- final class zenoh.handlers.DefaultHandler
The default handler type used by Zenoh when no explicit handler is provided.
DefaultHandler serves as an opaque wrapper around
FifoChannelwith default settings. When no channel or callback is specified for subscribers or queries, Zenoh automatically uses this handler.This type provides API stability by allowing the underlying default handler implementation to change without breaking existing code. Currently, it wraps a FIFO queue implementation.
For more information about channels and callbacks, see Channels and callbacks.
- final class zenoh.handlers.FifoChannel(capacity)
A handler implementing FIFO semantics.
FifoChannel provides a bounded FIFO (First-In-First-Out) queue for handling received data. When the channel reaches its capacity, pushing additional items will block until space becomes available.
Note: A slow consumer can block the underlying Zenoh thread if it doesn’t empty the FifoChannel fast enough. For applications where dropping old samples is preferable to blocking, consider using
RingChannelinstead.For more information about channels and callbacks, see Channels and callbacks.
- Args:
capacity: The maximum number of items the channel can hold.
- Parameters:
capacity (int) –
- Return type:
Self
- final class zenoh.handlers.Handler
Provides access to received Zenoh data.
Handler instances are returned by Zenoh operations that receive data asynchronously. Each instance provides methods to access the received data items of type
_T.Handler serves as a common interface for different channel implementations:
DefaultHandler,FifoChannel, andRingChannel. Regardless of which channel type is used, Handler provides the same methods for data access.Handler instances are returned by several Zenoh operations:
zenoh.Session.get()returns Handler[Reply] for accessing query replieszenoh.Querier.get()returns Handler[Reply] for accessing querier replieszenoh.Session.declare_subscriber()returns Subscriber[Handler[Sample]] for accessing received samples
Handler provides both blocking and non-blocking methods to receive data, as well as iteration support. The underlying implementation determines the specific behavior (FIFO blocking, ring buffer dropping, etc.).
- recv()
Receive an item, blocking if necessary.
Waits until an item is available and returns it. This method will block the calling thread until data arrives.
- Returns:
The next available item.
- Return type:
_T
- try_recv()
Attempt to receive an item without blocking.
Returns the next available item if one is ready, otherwise returns None. This method never blocks and is useful for polling or non-blocking loops.
- Returns:
The next item if available, None otherwise.
- Return type:
_T | None
- final class zenoh.handlers.RingChannel(capacity)
A synchronous ring channel with a limited size that allows users to keep the last N data items.
RingChannel implements FIFO semantics with a dropping strategy when full. When the channel reaches its capacity, the oldest elements are dropped to make room for newer ones, ensuring that only the most recent data is kept.
This makes RingChannel ideal for applications that need to maintain a sliding window of recent data without blocking the producer.
For applications where data loss is unacceptable and blocking is preferable to dropping old samples, consider using
FifoChannelinstead.For more information about channels and callbacks, see Channels and callbacks.
- Args:
capacity: The maximum number of items the channel can hold.
- Parameters:
capacity (int) –
- Return type:
Self
module zenoh.ext
- exception zenoh.ext.ZDeserializeError
Exception raised when deserialization with
zenoh.ext.z_deserialize()fails.
- final class zenoh.ext.AdvancedPublisher
An extension to Publisher providing advanced functionalities.
Advanced publishers are created via
declare_advanced_publisher()and works alongsideAdvancedSubscriber. Its features include:Caching - Store last published samples for retrieval via subscriber history mechanisms. Configure via
CacheConfig.Sample miss detection - Identify gaps in publications to detect missed samples. Configure via
MissDetectionConfig. Subscribers can monitor misses viaAdvancedSubscriber.sample_miss_listener().Publisher detection - Assert presence through liveliness tokens. Subscribers can detect publishers via
AdvancedSubscriber.detect_publishers().
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- delete(*, attachment=None, timestamp=None)
Delete the value associated with the key expression. See
zenoh.Publisher.delete().- Parameters:
attachment (Any | None) –
timestamp (Timestamp | None) –
- put(payload, *, encoding=None, attachment=None, timestamp=None)
Publish data to the key expression. See
zenoh.Publisher.put().
- undeclare()
Undeclare the AdvancedPublisher. See
zenoh.Publisher.undeclare().
- property congestion_control: CongestionControl
The congestion control policy applied to published data. See
zenoh.Publisher.congestion_control().
- property encoding: Encoding
The encoding used for published data. See
zenoh.Publisher.encoding().
- property id: EntityGlobalId
The globally unique id of this AdvancedPublisher. See
zenoh.Publisher.id(). .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property key_expr: KeyExpr
The key expression this AdvancedPublisher publishes to. See
zenoh.Publisher.key_expr().
- property priority: Priority
The priority level of published data. See
zenoh.Publisher.priority().
- final class zenoh.ext.AdvancedSubscriber
An extension to Subscriber providing advanced functionalities.
AdvancedSubscriber is created with
declare_advanced_subscriber()and works alongsideAdvancedPublisher. Its features include:missing samples detection using periodic queries or heartbeat subscription configurable via
RecoveryConfig. Notification about missed samples is done viaAdvancedSubscriber.sample_miss_listener().recovering missing samples with max age, sample count and late joiner detection configurable via
HistoryConfig.matching publishers detection using liveliness mechanisms. Use
AdvancedSubscriber.detect_publishers()to find active publishers.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- detect_publishers(handler=None, *, history=None)
Declare a listener to detect matching publishers.
Only
AdvancedPublisherinstances that enable publisher_detection in thedeclare_advanced_publisher()can be detected. This uses Liveliness to track publisher presence.- Parameters:
handler (DefaultHandler[Sample] | FifoChannel[Sample] | RingChannel[Sample] | tuple[Callable[[Sample], Any], Any] | Callable[[Sample], Any] | None) – Optional handler for receiving publisher detection events.
history (bool | None) – If True, the already present publishers will be reported upon declaration. Uses history feature of
zenoh.Liveliness.declare_subscriber().
- Return type:
- recv()
Receive a sample, blocking until one is available. See
zenoh.Subscriber.recv().- Parameters:
self (AdvancedSubscriber[Handler[Sample]]) –
- Return type:
- sample_miss_listener(handler=None)
Declare a listener to detect missed samples.
Missed samples can only be detected from
AdvancedPublisherinstances that enable sample_miss_detection. The listener will receiveMissnotifications indicating the source and number of missed samples.- Parameters:
handler (DefaultHandler[Miss] | FifoChannel[Miss] | RingChannel[Miss] | tuple[Callable[[Miss], Any], Any] | Callable[[Miss], Any] | None) –
- Return type:
- try_recv()
Try to receive a sample without blocking. See
zenoh.Subscriber.try_recv().- Parameters:
self (AdvancedSubscriber[Handler[Sample]]) –
- Return type:
Sample | None
- undeclare()
Undeclare the AdvancedSubscriber. See
zenoh.Subscriber.undeclare().
- property handler: _H
The handler used to process received samples. See
zenoh.Subscriber.handler().
- property id: EntityGlobalId
The globally unique id of this AdvancedSubscriber. See
zenoh.Subscriber.id(). .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property key_expr: KeyExpr
The key expression this AdvancedSubscriber subscribes to. See
zenoh.Subscriber.key_expr().
- final class zenoh.ext.CacheConfig(max_samples=None, *, replies_config=None)
Configure caching behavior for an
AdvancedPublisher.- param max_samples:
specify how many samples to keep for each resource, default to 1
- param replies_config:
the QoS to apply to replies
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
max_samples (int | None) –
replies_config (RepliesConfig | None) –
- Return type:
Self
- class zenoh.ext.Float32(x=0, /)
float subclass enabling to (de)serialize 32bit floating point numbers.
- class zenoh.ext.Float64(x=0, /)
float subclass enabling to (de)serialize 64bit floating point numbers.
- final class zenoh.ext.HistoryConfig(*, detect_late_publishers=None, max_samples=None, max_age=None)
Configure history retrieval behavior for an
AdvancedSubscriber.- param detect_late_publishers:
enable detection of late joiner publishers and query for their historical data; late joiner detection can only be achieved for AdvancedPublisher that enable publisher_detection history can only be retransmitted by AdvancedPublisher that enable cache
- param max_samples:
specify how many samples to query for each resource
- param max_age:
specify the maximum age of samples to query in seconds
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
detect_late_publishers (bool | None) –
max_samples (int | None) –
max_age (float | int | None) –
- Return type:
Self
- class zenoh.ext.Int128
int subclass enabling to (de)serialize 128bit signed integer.
- class zenoh.ext.Int16
int subclass enabling to (de)serialize 16bit signed integer.
- class zenoh.ext.Int32
int subclass enabling to (de)serialize 32bit signed integer.
- class zenoh.ext.Int64
int subclass enabling to (de)serialize 64bit signed integer.
- class zenoh.ext.Int8
int subclass enabling to (de)serialize 8bit signed integer.
- final class zenoh.ext.Miss
Notification about missed samples detected by an
AdvancedSubscriber.A Miss indicates that one or more samples from an
AdvancedPublisherwere not received by the subscriber. This can occur due to network congestion, packet loss, or when the subscriber cannot keep up with the publication rate.Miss detection requires the publisher to enable sample_miss_detection in
declare_advanced_publisher()and the subscriber to have aSampleMissListenerviaAdvancedSubscriber.sample_miss_listener().Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- property nb: int
The number of consecutive samples that were missed from this source.
- property source: EntityGlobalId
The globally unique identifier of the
AdvancedPublisherthat published the missed samples.
- final class zenoh.ext.MissDetectionConfig(*, heartbeat, sporadic_heartbeat)
Configure miss detection behavior for an
AdvancedPublisher.- param heartbeat:
period in seconds, allow last sample miss detection through periodic heartbeat; periodically send the last published
zenoh.Sample’s sequence number to allow last sample recovery.zenoh.ext.AdvancedSubscribercan only recover the last sample with the heartbeat option enabled.This option can not be enabled simultaneously with `sporadic_heartbeat`.
- param sporadic_heartbeat:
period in seconds, allow last sample miss detection through sporadic heartbeat; each period, the last published
zenoh.Sample’s sequence number is sent with zenoh.CongestionControl.Block but only if it has changed since the last period.zenoh.ext.AdvancedSubscribercan only recover the last sample with the heartbeat option enabled.This option can not be enabled simultaneously with `heartbeat`.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
heartbeat (float | int | None) –
sporadic_heartbeat (float | int | None) –
- Return type:
Self
- final class zenoh.ext.RecoveryConfig(*, periodic_queries, heartbeat)
Configure recovery behavior for an
AdvancedSubscriber.- param periodic_queries:
enable periodic queries for not yet received Samples and specify their period; it allows retrieving the last Sample(s) if the last Sample(s) is/are lost, so it is useful for sporadic publications but useless for periodic publications with a period smaller or equal to this period. Retransmission can only be achieved by
AdvancedPublisherthat enable cache and sample_miss_detection.This option can not be enabled simultaneously with `heartbeat`.
- param heartbeat:
subscribe to heartbeats of
AdvancedPublisher; it allows receiving the last published Sample’s sequence number and check for misses. Heartbeat subscriber must be paired withAdvancedPublisherthat enable cache and sample_miss_detection with heartbeat or sporadic_heartbeat.This option can not be enabled simultaneously with `periodic_queries`.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
periodic_queries (float | int | None) –
heartbeat (Literal[True] | None) –
- Return type:
Self
- final class zenoh.ext.RepliesConfig(*, congestion_control=None, priority=None, express=None)
Configure QoS settings for replies from a
AdvancedSubscriber. Parameter inzenoh.CacheConfig.Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
- Return type:
Self
- final class zenoh.ext.SampleMissListener
Listener for detecting missed samples from an
AdvancedSubscriber.Instances are created via
AdvancedSubscriber.sample_miss_listener().This listener receives
Missnotifications when gaps are detected in the sequence of samples fromAdvancedPublisherinstances. This works for publishers that enable sample_miss_detection indeclare_advanced_publisher().Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- recv()
Receive a miss notification, blocking until one is available.
- Parameters:
self (SampleMissListener[Handler[Miss]]) –
- Return type:
- try_recv()
Try to receive a miss notification without blocking.
- Parameters:
self (SampleMissListener[Handler[Miss]]) –
- Return type:
Miss | None
- undeclare()
Undeclare the SampleMissListener.
- class zenoh.ext.UInt128
int subclass enabling to (de)serialize 128bit unsigned integer.
- class zenoh.ext.UInt16
int subclass enabling to (de)serialize 16bit unsigned integer.
- class zenoh.ext.UInt32
int subclass enabling to (de)serialize 32bit unsigned integer.
- class zenoh.ext.UInt64
int subclass enabling to (de)serialize 64bit unsigned integer.
- class zenoh.ext.UInt8
int subclass enabling to (de)serialize 8bit unsigned integer.
- zenoh.ext.declare_advanced_publisher(session, key_expr, *, encoding=None, congestion_control=None, priority=None, express=None, reliability=None, allowed_destination=None, cache=None, sample_miss_detection=None, publisher_detection=None)
Declare an
AdvancedPublisherfor the given key expression. .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.- Parameters:
session (Session) –
key_expr (KeyExpr | str) –
encoding (Encoding | str | None) –
congestion_control (CongestionControl | None) –
priority (Priority | None) –
express (bool | None) –
reliability (Reliability | None) –
allowed_destination (Locality | None) –
cache (CacheConfig | None) –
sample_miss_detection (MissDetectionConfig | None) –
publisher_detection (bool | None) –
- Return type:
- zenoh.ext.declare_advanced_subscriber(session, key_expr, handler=None, *, allowed_origin=None, history=None, recovery=None, subscriber_detection=None)
Declare an
AdvancedSubscriberfor the given key expression.- Parameters:
session (Session) –
key_expr (KeyExpr | str) –
handler (DefaultHandler[Sample] | FifoChannel[Sample] | RingChannel[Sample] | tuple[Callable[[Sample], Any], Any] | Callable[[Sample], Any] | None) –
allowed_origin (Locality | None) –
history (HistoryConfig | None) –
recovery (RecoveryConfig | None) –
subscriber_detection (bool | None) –
- Return type:
- zenoh.ext.z_deserialize(tp, zbytes)
Deserialize into an object of supported type according to the Zenoh serialization format.
Supported types are:
UInt8, UInt16, Uint32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128, int (handled as int32), Float32, Float64, float (handled as Float64), bool;
Str, Bytes, ByteArray;
List, Dict, Set, FrozenSet and Tuple of supported types.
- Parameters:
tp (type[_T]) –
zbytes (ZBytes) –
- Return type:
_T
- zenoh.ext.z_serialize(obj)
Serialize an object of supported type according to the Zenoh serialization format.
Supported types are:
UInt8, UInt16, Uint32, UInt64, UInt128, Int8, Int16, Int32, Int64, Int128, int (handled as int32), Float32, Float64, float (handled as Float64), bool;
Str, Bytes, ByteArray;
List, Dict, Set, FrozenSet and Tuple of supported types.
- Parameters:
obj (Any) –
- Return type:
module zenoh.shm
- final class zenoh.shm.AllocAlignment(pow)
alignment in powers of 2: 0 == 1-byte alignment, 1 == 2byte, 2 == 4byte, 3 == 8byte etc .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
pow (int) –
- Return type:
Self
- align_size(size)
Align size according to inner alignment. This call may extend the size
- Parameters:
size (int) –
- Return type:
int
- get_alignment_value()
Get alignment in normal units (bytes)
- Return type:
int
- ALIGN_1_BYTE: Self
- ALIGN_2_BYTE: Self
- ALIGN_4_BYTE: Self
- ALIGN_8_BYTE: Self
- final class zenoh.shm.BlockOn(inner_policy=<zenoh.shm.JustAlloc object>)
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
inner_policy (_AllocPolicy) –
- Return type:
Self
- final class zenoh.shm.Deallocate(inner_policy=<zenoh.shm.JustAlloc object>, alt_policy=<zenoh.shm.JustAlloc object>)
- Deallocating policy.
Forcibly deallocate up to N buffers until allocation succeeds.
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
inner_policy (_AllocPolicy) –
alt_policy (_AllocPolicy) –
- Return type:
Self
- final class zenoh.shm.Defragment(inner_policy=<zenoh.shm.JustAlloc object>, alt_policy=<zenoh.shm.JustAlloc object>)
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
inner_policy (_AllocPolicy) –
alt_policy (_AllocPolicy) –
- Return type:
Self
- final class zenoh.shm.GarbageCollect(inner_policy=<zenoh.shm.JustAlloc object>, alt_policy=<zenoh.shm.JustAlloc object>, *, safe=True)
Warning
This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
inner_policy (_AllocPolicy) –
alt_policy (_AllocPolicy) –
safe (bool) –
- Return type:
Self
- final class zenoh.shm.JustAlloc
Just try to allocate .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- final class zenoh.shm.MemoryLayout(size, alignment)
Memory layout representation: alignment and size aligned for this alignment .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- Parameters:
size (int) –
alignment (AllocAlignment) –
- Return type:
Self
- property alignment: AllocAlignment
- property size: int
- final class zenoh.shm.ShmProvider
A generalized interface for shared memory data sources .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- alloc(layout, policy=<zenoh.shm.JustAlloc object>)
Rich interface for making allocations
- Parameters:
layout (MemoryLayout | tuple[int, AllocAlignment] | int) –
policy (JustAlloc | BlockOn | Defragment | GarbageCollect) –
- Return type:
- classmethod default_backend(layout)
Set the default backend
- Parameters:
layout (MemoryLayout | tuple[int, AllocAlignment] | int) –
- Return type:
Self
- defragment()
Defragment memory
- garbage_collect()
Try to collect free chunks. Returns the size of largest collected chunk
- Return type:
int
- garbage_collect_unsafe()
Try to collect free chunks. Returns the size of largest collected chunk
- Return type:
int
- property available: int
Bytes available for use
- final class zenoh.shm.ZShm
A SHM buffer .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.
- is_valid()
- Return type:
bool
- final class zenoh.shm.ZShmMut
A mutable SHM buffer .. warning:: This API has been marked as unstable: it works as advertised, but it may be changed in a future release.