Skip to content

Commit b3b1642

Browse files
committed
add examples
1 parent fafad63 commit b3b1642

6 files changed

Lines changed: 166 additions & 10 deletions

File tree

examples/z_advanced_pub.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#
2+
# Copyright (c) 2022 ZettaScale Technology
3+
#
4+
# This program and the accompanying materials are made available under the
5+
# terms of the Eclipse Public License 2.0 which is available at
6+
# http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7+
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
8+
#
9+
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10+
#
11+
# Contributors:
12+
# ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13+
#
14+
import time
15+
from typing import Optional
16+
17+
import zenoh
18+
from zenoh.ext import CacheConfig, MissDetectionConfig, declare_advanced_publisher
19+
20+
21+
def main(conf: zenoh.Config, key: str, payload: str, history: int):
22+
# initiate logging
23+
zenoh.init_log_from_env_or("error")
24+
25+
print("Opening session...")
26+
with zenoh.open(conf) as session:
27+
print(f"Declaring AdvancedPublisher on '{key}'...")
28+
pub = declare_advanced_publisher(
29+
session,
30+
key,
31+
cache=CacheConfig(max_samples=history),
32+
sample_miss_detection=MissDetectionConfig(heartbeat=5),
33+
publisher_detection=True,
34+
)
35+
36+
print("Press CTRL-C to quit...")
37+
for idx in itertools.count():
38+
buf = f"[{idx:4d}] {payload}"
39+
print(f"Putting Data ('{key}': '{buf}')...")
40+
pub.put(buf)
41+
42+
43+
# --- Command line argument parsing --- --- --- --- --- ---
44+
if __name__ == "__main__":
45+
import argparse
46+
import itertools
47+
48+
import common
49+
50+
parser = argparse.ArgumentParser(prog="z_pub", description="zenoh pub example")
51+
common.add_config_arguments(parser)
52+
parser.add_argument(
53+
"--key",
54+
"-k",
55+
dest="key",
56+
default="demo/example/zenoh-python-pub",
57+
type=str,
58+
help="The key expression to publish onto.",
59+
)
60+
parser.add_argument(
61+
"--payload",
62+
"-p",
63+
dest="payload",
64+
default="Pub from Python!",
65+
type=str,
66+
help="The payload to publish.",
67+
)
68+
parser.add_argument(
69+
"--history",
70+
dest="history",
71+
type=int,
72+
default=1,
73+
help="The number of publications to keep in cache",
74+
)
75+
76+
args = parser.parse_args()
77+
conf = common.get_config_from_args(args)
78+
79+
main(conf, args.key, args.payload, args.history, args.iter, args.interval)

examples/z_advanced_sub.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#
2+
# Copyright (c) 2022 ZettaScale Technology
3+
#
4+
# This program and the accompanying materials are made available under the
5+
# terms of the Eclipse Public License 2.0 which is available at
6+
# http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7+
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
8+
#
9+
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10+
#
11+
# Contributors:
12+
# ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13+
#
14+
import time
15+
16+
import zenoh
17+
from zenoh.ext import HistoryConfig, Miss, RecoveryConfig, declare_advanced_subscriber
18+
19+
20+
def main(conf: zenoh.Config, key: str):
21+
# initiate logging
22+
zenoh.init_log_from_env_or("error")
23+
24+
print("Opening session...")
25+
with zenoh.open(conf) as session:
26+
print(f"Declaring Subscriber on '{key}'...")
27+
28+
def listener(sample: zenoh.Sample):
29+
print(
30+
f">> [Subscriber] Received {sample.kind} ('{sample.key_expr}': '{sample.payload.to_string()}')"
31+
)
32+
33+
advanced_sub = declare_advanced_subscriber(
34+
session,
35+
key,
36+
listener,
37+
history=HistoryConfig(detect_late_publishers=True),
38+
recovery=RecoveryConfig(heartbeat=True),
39+
subscriber_detection=True,
40+
)
41+
42+
def miss_listener(miss: Miss):
43+
print(f">> [Subscriber] Missed {miss.nb} samples from {miss.source} !!!")
44+
45+
advanced_sub.sample_miss_listener(miss_listener)
46+
47+
print("Press CTRL-C to quit...")
48+
while True:
49+
time.sleep(1)
50+
51+
52+
# --- Command line argument parsing --- --- --- --- --- ---
53+
if __name__ == "__main__":
54+
import argparse
55+
56+
import common
57+
58+
parser = argparse.ArgumentParser(prog="z_sub", description="zenoh sub example")
59+
common.add_config_arguments(parser)
60+
parser.add_argument(
61+
"--key",
62+
"-k",
63+
dest="key",
64+
default="demo/example/**",
65+
type=str,
66+
help="The key expression to subscribe to.",
67+
)
68+
69+
args = parser.parse_args()
70+
conf = common.get_config_from_args(args)
71+
72+
main(conf, args.key)

src/ext.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::{
1818
bytes::{Encoding, ZBytes},
1919
handlers::{into_handler, HandlerImpl},
2020
key_expr::KeyExpr,
21-
macros::{build, downcast_or_new, import, option_wrapper, py_static, try_import, wrapper},
21+
macros::{build, import, option_wrapper, py_static, try_import, wrapper},
2222
pubsub::Subscriber,
2323
qos::{CongestionControl, Priority, Reliability},
2424
sample::Sample,
@@ -594,7 +594,6 @@ impl AdvancedSubscriber {
594594
}
595595

596596
wrapper!(zenoh_ext::CacheConfig: Clone);
597-
downcast_or_new!(CacheConfig => Option<usize>, None);
598597

599598
#[pymethods]
600599
impl CacheConfig {
@@ -634,12 +633,12 @@ wrapper!(zenoh_ext::Miss);
634633
impl Miss {
635634
#[getter]
636635
fn source(&self) -> EntityGlobalId {
637-
self.source().into()
636+
self.0.source().into()
638637
}
639638

640639
#[getter]
641-
fn nb(&self) -> usize {
642-
self.nb()
640+
fn nb(&self) -> u32 {
641+
self.0.nb()
643642
}
644643
}
645644

@@ -745,7 +744,7 @@ impl SampleMissListener {
745744
#[allow(clippy::too_many_arguments)]
746745
#[pyfunction]
747746
#[pyo3(signature = (session, key_expr, *, encoding = None, congestion_control = None, priority = None, express = None, reliability = None, cache = None, sample_miss_detection = None, publisher_detection = None))]
748-
fn declare_publisher(
747+
pub(crate) fn declare_advanced_publisher(
749748
py: Python,
750749
session: &Session,
751750
#[pyo3(from_py_with = "KeyExpr::from_py")] key_expr: KeyExpr,
@@ -777,7 +776,7 @@ fn declare_publisher(
777776
#[allow(clippy::too_many_arguments)]
778777
#[pyfunction]
779778
#[pyo3(signature = (session, key_expr, handler = None, *, history = None, recovery = None, subscriber_detection = None))]
780-
fn declare_subscriber(
779+
pub(crate) fn declare_advanced_subscriber(
781780
session: &Session,
782781
py: Python,
783782
#[pyo3(from_py_with = "KeyExpr::from_py")] key_expr: KeyExpr,

src/lib.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,11 @@ pub(crate) mod zenoh {
8080
#[pymodule]
8181
mod _ext {
8282
#[pymodule_export]
83-
use crate::ext::{z_deserialize, z_serialize};
83+
use crate::ext::{
84+
declare_advanced_publisher, declare_advanced_subscriber, z_deserialize, z_serialize,
85+
AdvancedPublisher, AdvancedSubscriber, CacheConfig, HistoryConfig, Miss,
86+
MissDetectionConfig, RecoveryConfig, RepliesConfig, SampleMissListener,
87+
};
8488
#[pymodule_export]
8589
use crate::ZDeserializeError;
8690
}

src/session.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,5 +313,7 @@ impl EntityGlobalId {
313313
self.0.eid()
314314
}
315315

316-
// TODO __repr__
316+
fn __repr__(&self) -> String {
317+
format!("{:?}", self.0)
318+
}
317319
}

zenoh/ext.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ def declare_advanced_publisher(
304304
priority: Priority | None = None,
305305
express: bool | None = None,
306306
reliability: Reliability | None = None,
307-
cache: CacheConfig | int | None = None,
307+
cache: CacheConfig | None = None,
308308
sample_miss_detection: MissDetectionConfig | None = None,
309309
publisher_detection: bool | None = None,
310310
) -> AdvancedPublisher:

0 commit comments

Comments
 (0)