Zenoh API Reference
[Zenoh](https://zenoh.io) /zeno/ is a stack that unifies data in motion, data at rest and computations. It elegantly blends traditional pub/sub with geo distributed storage, queries and computations, while retaining a level of time and space efficiency that is well beyond any of the mainstream stacks.
Before delving into the examples, we need to introduce few Zenoh concepts.
First off, in Zenoh you will deal with Resources, where a resource is made up of a
key and a value. The other concept you’ll have to familiarize yourself with are
key expressions, such as robot/sensor/temp, robot/sensor/*, robot/**, etc.
As you can gather, the above key expression denotes set of keys, while the * and **
are wildcards representing respectively (1) a single chunk (non-empty sequence of characters that doesn’t contain /), and (2) any amount of chunks (including 0).
Below are some examples that highlight these key concepts and show how easy it is to get started with.
Quick start examples:
Publish a key/value pair onto Zenoh
>>> import zenoh
>>> with zenoh.open() as z:
>>> z.put('demo/example/hello', 'Hello World!')
Subscribe to a set of keys with Zenoh
>>> import zenoh, time
>>> def listener(sample):
>>> print(f"{sample.key_expr} => {sample.payload.decode('utf-8')}")
>>>
>>> with zenoh.open() as z:
>>> with z.subscribe('demo/example/**', listener) as subscriber:
>>> time.sleep(60)
Get keys/values from zenoh
>>> import zenoh
>>> with zenoh.open() as z:
>>> for response in z.get('demo/example/**'):
>>> response = response.ok
>>> print(f"{response.key_expr} => {response.payload.deserialize(str)}")
module zenoh
Zenoh /zeno/ is a stack that unifies data in motion, data at rest and computations. It elegantly blends traditional pub/sub with geo distributed storage, queries and computations, while retaining a level of time and space efficiency that is well beyond any of the mainstream stacks.
Before delving into the examples, we need to introduce few Zenoh concepts. First off, in Zenoh you will deal with Resources, where a resource is made up of a key and a value. The other concept you’ll have to familiarize yourself with are key expressions, such as robot/sensor/temp, robot/sensor/, robot/*, etc. As you can gather, the above key expression denotes set of keys, while the * and ** are wildcards representing respectively (1) an arbitrary string of characters, with the exclusion of the / separator, and (2) an arbitrary sequence of characters including separators.
- final exception zenoh.ZError
- final class zenoh.Config
The main configuration structure for Zenoh.
- final enum zenoh.CongestionControl(value)
The kind of congestion control.
Valid values are as follows:
- DROP = <CongestionControl.DROP: 1>
- BLOCK = <CongestionControl.BLOCK: 2>
- final enum zenoh.ConsolidationMode(value)
The kind of consolidation.
Valid values are as follows:
- AUTO = <ConsolidationMode.AUTO: 1>
- NONE = <ConsolidationMode.NONE: 2>
- MONOTONIC = <ConsolidationMode.MONOTONIC: 3>
- LATEST = <ConsolidationMode.LATEST: 4>
- final class zenoh.Encoding(encoding=None)
Default encoding values used by Zenoh. An encoding has a similar role to Content-type in HTTP: it indicates, when present, how data should be interpreted by the application. Please note the Zenoh protocol does not impose any encoding value nor it operates on it. It can be seen as some optional metadata that is carried over by Zenoh in such a way the application may perform different operations depending on the encoding value. A set of associated constants are provided to cover the most common encodings for user convenience. This is parcticular useful in helping Zenoh to perform additional network optimizations.
- 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 semantichs is 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 data, common 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 that are 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
A h261-encoded video stream.
Constant alias for string: “video/h261”.
- VIDEO_H263: Self
A h263-encoded video stream.
Constant alias for string: “video/h263”.
- VIDEO_H264: Self
A h264-encoded video stream.
Constant alias for string: “video/h264”.
- VIDEO_H265: Self
A h265-encoded video stream.
Constant alias for string: “video/h265”.
- VIDEO_H266: Self
A 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_BOOL: Self
A boolean. 0 is false, 1 is true. Other values are invalid.
Constant alias for string: “zenoh/bool”.
- ZENOH_BYTES: Self
Just some bytes.
Constant alias for string: “zenoh/bytes”.
- ZENOH_ERROR: Self
A zenoh error.
Constant alias for string: “zenoh/error”.
- ZENOH_FLOAT: Self
A VLE-encoded float. Either little-endian 32bit or 64bit. Binary representation uses IEEE 754-2008 binary32 or binary64, respectively.
Constant alias for string: “zenoh/float”.
- ZENOH_INT: Self
A VLE-encoded signed little-endian integer. Either 8bit, 16bit, 32bit, or 64bit. Binary reprensentation uses two’s complement.
Constant alias for string: “zenoh/int”.
- ZENOH_STRING: Self
A UTF-8 string.
Constant alias for string: “zenoh/string”.
- ZENOH_UINT: Self
A VLE-encoded little-endian unsigned integer. Either 8bit, 16bit, 32bit, or 64bit.
Constant alias for string: “zenoh/uint”.
- final class zenoh.KeyExpr(key_expr)
A possibly-owned version of keyexpr that may carry optimisations for use with a Session that may have declared it. Check keyexpr’s documentation for detailed explainations of the Key Expression Language
- Parameters:
key_expr (str)
- Return type:
Self
- autocanonize(key_expr)
Canonizes the passed value before returning it as a KeyExpr. Will return Err if 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 if possible. You should probably prefer KeyExpr::join as Zenoh may then take advantage of the hierachical separation it ins erts.
- Parameters:
other (str)
- Return type:
- includes(key_expr)
Returns true if self includes other, i.e. the set defined by self contains every key belonging to the set defined by other.
- Parameters:
key_expr (KeyExpr | str)
- Return type:
bool
- intersects(key_expr)
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:
key_expr (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(key_expr)
Returns the relation between self and other from self’s point of view (SetIntersectionLevel::Includes signifies that self includes other). Note that this is slower than keyexpr::intersects and keyexpr::includes, so you should favor these methods for most applications.
- Parameters:
key_expr (KeyExpr | str)
- Return type:
- final enum zenoh.Priority(value)
The Priority of zenoh messages.
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 to send data through a stream. Publishers are automatically undeclared when dropped.
- delete(*, attachment=None)
Delete data.
- Parameters:
attachment (Any | None)
- put(payload, *, encoding=None, attachment=None)
Put data.
- Parameters:
payload (Any)
encoding (Encoding | str | None)
attachment (Any | None)
- undeclare()
Undeclares the Publisher, informing the network that it needn’t optimize publications for its key expression anymore.
- final class zenoh.Query
Structs received by a Queryable.
- reply(key_expr, payload, *, encoding=None, congestion_control=None, priority=None, express=None, attachment=None)
Sends 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 Query::accepts_replies), replying on a disjoint key expression will result in an error when resolving the reply.
- Parameters:
key_expr (KeyExpr | str)
payload (Any)
encoding (Encoding | str | None)
congestion_control (CongestionControl | None)
priority (Priority | None)
express (bool | None)
attachment (Any | None)
- reply_del(key_expr, *, congestion_control=None, priority=None, express=None, attachment=None)
Sends a delete 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 Query::accepts_replies), replying on a disjoint key expression will result in an error when resolving the reply.
- Parameters:
key_expr (KeyExpr | str)
congestion_control (CongestionControl | None)
priority (Priority | None)
express (bool | None)
attachment (Any | None)
- final enum zenoh.QueryTarget(value)
The kind of consolidation.
Valid values are as follows:
- BEST_MATCHING = <QueryTarget.BEST_MATCHING: 1>
- ALL = <QueryTarget.ALL: 2>
- ALL_COMPLETE = <QueryTarget.ALL_COMPLETE: 3>
- final class zenoh.Queryable
A queryable that provides data through a Handler. Queryables can be created from a zenoh Session with the declare_queryable function and the with function of the resulting builder. Queryables are automatically undeclared when dropped.
- final enum zenoh.Reliability(value)
Valid values are as follows:
- BEST_EFFORT = <Reliability.BEST_EFFORT: 1>
- RELIABLE = <Reliability.RELIABLE: 2>
- final class zenoh.Reply
Structs returned by a get.
- final enum zenoh.SampleKind(value)
Valid values are as follows:
- PUT = <SampleKind.PUT: 1>
- DELETE = <SampleKind.DELETE: 2>
- final class zenoh.Scout
- final class zenoh.Selector(arg, /, parameters=None)
A selector is the combination of a Key Expression, which defines the set of keys that are relevant to an operation, and a set of parameters with a few intendend uses: specifying arguments to a queryable, allowing the passing of Remote Procedure Call parameters filtering 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_expr before the first ? must be a valid key expression. the parameters after 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 string, both name and value should use percent-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. The full specification for selectors is available here , it includes standardized parameters. Queryable implementers 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): _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. [unstable] _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. _anyke disables the query-reply key expression matching check.
- Parameters:
arg (_IntoKeyExpr | str)
parameters (_IntoParameters | None)
- final class zenoh.Session
A zenoh session.
- close()
Close the zenoh Session. Sessions are automatically closed when dropped, but you may want to use this function to handle errors or close the Session asynchronously.
- config()
Get the current configuration of the zenoh Session. 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 funtion.
- Return type:
- declare_keyexpr(key_expr)
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.
- Parameters:
key_expr (KeyExpr | str)
- declare_publisher(key_expr, *, congestion_control=None, priority=None, express=None)
Create a Publisher for the given key expression.
- Parameters:
key_expr (KeyExpr | str)
congestion_control (CongestionControl | None)
priority (Priority | None)
express (bool | None)
- Return type:
- declare_queryable(key_expr, handler=None, *, complete=None)
Create a Queryable for 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)
- Return type:
- declare_subscriber(key_expr, handler=None, *, reliability=None)
Create a Subscriber for 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)
reliability (Reliability | None)
- Return type:
- delete(key_expr, *, congestion_control=None, priority=None, express=None, attachment=None)
Delete data.
- Parameters:
key_expr (KeyExpr | str)
congestion_control (CongestionControl | None)
priority (Priority | None)
express (bool | None)
attachment (Any | None)
- get(selector, handler=None, *, target=None, consolidation=None, timeout=None, congestion_control=None, priority=None, express=None, payload=None, encoding=None, attachment=None)
Query data from the matching queryables in the system. Unless explicitly requested via GetBuilder::accept_replies, replies are guaranteed to have key expressions that match the requested selector.
- Parameters:
handler (DefaultHandler[Reply] | FifoChannel[Reply] | RingChannel[Reply] | tuple[Callable[[Reply], Any], Any] | Callable[[Reply], Any] | None)
target (QueryTarget | None)
consolidation (ConsolidationMode | None)
timeout (float | int | None)
congestion_control (CongestionControl | None)
priority (Priority | None)
express (bool | None)
payload (Any)
encoding (Encoding | str | None)
attachment (Any | None)
- Return type:
- put(key_expr, payload, *, encoding=None, congestion_control=None, priority=None, express=None, attachment=None)
Put data.
- Parameters:
key_expr (KeyExpr | str)
payload (Any)
encoding (Encoding | str | None)
congestion_control (CongestionControl | None)
priority (Priority | None)
express (bool | None)
attachment (Any | None)
- final enum zenoh.SetIntersectionLevel(value)
Valid values are as follows:
- DISJOINT = <SetIntersectionLevel.DISJOINT: 1>
- INTERSECTS = <SetIntersectionLevel.INTERSECTS: 2>
- INCLUDES = <SetIntersectionLevel.INCLUDES: 3>
- EQUALS = <SetIntersectionLevel.EQUALS: 4>
- final class zenoh.Subscriber
A subscriber that provides data through a Handler. Subscribers can be created from a zenoh Session with the declare_subscriber function and the with function of the resulting builder. Subscribers are automatically undeclared when dropped.
- 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.
- final enum zenoh.WhatAmI(value)
Valid values are as follows:
- ROUTER = <WhatAmI.ROUTER: 1>
- PEER = <WhatAmI.PEER: 2>
- CLIENT = <WhatAmI.CLIENT: 3>
- final class zenoh.ZBytes(obj=None)
ZBytes contains the serialized bytes of user data.
- Parameters:
obj (Any)
- Return type:
Self
- deserialize(tp)
Deserialize payload to the given types, using default or registered deserializer
- Parameters:
tp (type[_T])
- Return type:
_T
- final class zenoh.ZenohId
The global unique id of a zenoh peer.
- zenoh.deserializer(func: _F, /) _F
- zenoh.deserializer(*, target: type) Callable[[_F], _F]
Register a deserializer for a given type, which will be used to deserialize payload.
If the function is type-annotated, it will use the return type. Otherwise, the type has to be passed with the ‘target’ parameter.
- zenoh.open(config=None)
Open a zenoh Session.
- 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 Hello replies. Drop the returned Scout to stop the scouting task.
- 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.serializer(func: _F, /) _F
- zenoh.serializer(*, target: type) Callable[[_F], _F]
Register a serializer for a given type, which will be used to serialize payloads.
If the function is type-annotated, it will use the type of the first argument. Otherwise, the type has to be passed with the ‘target’ parameter.
- 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)
- Parameters:
callback (Callable[[_T], Any])
drop (Callable[[], Any] | None)
indirect (bool)
- Return type:
Self
- final class zenoh.handlers.DefaultHandler
The default handler in Zenoh is a FIFO queue.
- final class zenoh.handlers.FifoChannel(capacity)
The default handler in Zenoh is a FIFO queue.
- Parameters:
capacity (int)
- Return type:
Self
- final class zenoh.handlers.Handler
Handler for DefaultHandler/FifoHandler/RingHandler.
- final class zenoh.handlers.RingChannel(capacity)
A synchrounous ring channel with a limited size that allows users to keep the last N data.
- Parameters:
capacity (int)
- Return type:
Self