|
| 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, <[email protected]> |
| 13 | +# |
| 14 | +import zenoh |
| 15 | + |
| 16 | + |
| 17 | +def main(conf: zenoh.Config, key: str): |
| 18 | + # initiate logging |
| 19 | + zenoh.init_log_from_env_or("error") |
| 20 | + |
| 21 | + print("Opening session...") |
| 22 | + with zenoh.open(conf) as session: |
| 23 | + print(f"Declaring Subscriber on '{key}'...") |
| 24 | + with session.declare_subscriber(key) as sub: |
| 25 | + print("Press CTRL-C to quit...") |
| 26 | + for sample in sub: |
| 27 | + payload_type, payload = handle_bytes(sample.payload) |
| 28 | + print( |
| 29 | + f">> [Subscriber] Received {sample.kind} ('{sample.key_expr}': '{payload}')[{payload_type}] ", |
| 30 | + end="", |
| 31 | + ) |
| 32 | + if att := sample.attachment: |
| 33 | + attachment_type, attachment = handle_bytes(att) |
| 34 | + print(f" ({attachment_type}: {attachment})") |
| 35 | + print() |
| 36 | + |
| 37 | + |
| 38 | +def handle_bytes(bytes: zenoh.ZBytes) -> tuple[str, str]: |
| 39 | + bytes_type = "SHM" if bytes.as_shm() is not None else "RAW" |
| 40 | + return bytes_type, bytes.to_string() |
| 41 | + |
| 42 | + |
| 43 | +# --- Command line argument parsing --- --- --- --- --- --- |
| 44 | +if __name__ == "__main__": |
| 45 | + import argparse |
| 46 | + import json |
| 47 | + |
| 48 | + import common |
| 49 | + |
| 50 | + parser = argparse.ArgumentParser( |
| 51 | + prog="z_sub_queued", description="zenoh sub example" |
| 52 | + ) |
| 53 | + common.add_config_arguments(parser) |
| 54 | + parser.add_argument( |
| 55 | + "--key", |
| 56 | + "-k", |
| 57 | + dest="key", |
| 58 | + default="demo/example/**", |
| 59 | + type=str, |
| 60 | + help="The key expression to subscribe to.", |
| 61 | + ) |
| 62 | + |
| 63 | + args = parser.parse_args() |
| 64 | + conf = common.get_config_from_args(args) |
| 65 | + |
| 66 | + main(conf, args.key) |
0 commit comments