Beispiel #1
0
    def init_connection(self):
        # initiate logging
        zenoh.init_logger()

        L.warning("[ZENOH] Openning session...")
        self.z_session = zenoh.net.open(self.conf)

        self.z_sub_info = SubInfo(Reliability.Reliable, SubMode.Push)
Beispiel #2
0
async def main():
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(prog='z_info',
                                     description='zenoh info example')
    parser.add_argument('--mode',
                        '-m',
                        dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument('--connect',
                        '-e',
                        dest='connect',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to connect to.')
    parser.add_argument('--listen',
                        '-l',
                        dest='listen',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to listen on.')
    parser.add_argument('--config',
                        '-c',
                        dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else zenoh.Config()
    if args.mode is not None:
        conf.insert_json5(zenoh.config.MODE_KEY, json.dumps(args.mode))
    if args.connect is not None:
        conf.insert_json5(zenoh.config.CONNECT_KEY, json.dumps(args.connect))
    if args.listen is not None:
        conf.insert_json5(zenoh.config.LISTEN_KEY, json.dumps(args.listen))
    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    session = await zenoh.async_open(conf)

    info = await session.info()
    for key in info:
        print("{} : {}".format(key, info[key]))

    await session.close()
Beispiel #3
0
async def main():
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(
        prog='z_put',
        description='zenoh put example')
    parser.add_argument('--mode', '-m', dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument('--connect', '-e', dest='connect',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to connect to.')
    parser.add_argument('--listen', '-l', dest='listen',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to listen on.')
    parser.add_argument('--key', '-k', dest='key',
                        default='/demo/example/zenoh-python-put',
                        type=str,
                        help='The key expression matching resources to delete.')
    parser.add_argument('--config', '-c', dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else zenoh.Config()
    if args.mode is not None:
        conf.insert_json5(zenoh.config.MODE_KEY, json.dumps(args.mode))
    if args.connect is not None:
        conf.insert_json5(zenoh.config.CONNECT_KEY, json.dumps(args.connect))
    if args.listen is not None:
        conf.insert_json5(zenoh.config.LISTEN_KEY, json.dumps(args.listen))
    key = args.key

    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    session = await zenoh.async_open(conf)

    print("Deleting resources matching '{}'...".format(key))
    await session.delete(key)

    await session.close()
Beispiel #4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--payload', default=8, type=int)
    parser.add_argument('-s', '--scenario', default="dataflow")
    parser.add_argument('-n', '--name', default="test")
    parser.add_argument('-t', '--transport', default="tcp")
    parser.add_argument('-o', '--operators', action='store_true')
    parser.add_argument('-g', '--graph-file')
    args = parser.parse_args()

    zenoh.init_logger()

    # creating Zenoh.net session
    #session = zenoh.net.open({})
    """Creates and runs the dataflow graph."""
    (count_stream, ) = erdos.connect(SendOp,
                                     erdos.OperatorConfig(), [],
                                     size=args.payload)

    if args.operators:
        erdos.connect(ZenohSendOp,
                      erdos.OperatorConfig(), [count_stream],
                      size=args.payload)
        if args.graph_file is not None:
            erdos.run(args.graph_file)
        else:
            erdos.run()
    else:
        extract_stream = erdos.ExtractStream(count_stream)
        # creating zenoh session
        session = zenoh.net.open({})

        # Declaring zenoh sender
        rid = session.declare_resource(f'/thr/test/{args.payload}')
        publisher = session.declare_publisher(rid)

        if args.graph_file is not None:
            erdos.run_async(args.graph_file)
        else:
            erdos.run_async()

        counter = Counter(size=args.payload,
                          scenario=args.scenario,
                          name=args.name,
                          transport=args.transport)
        while True:
            msg = extract_stream.read()
            counter.inc()
Beispiel #5
0
if args.listener is not None:
    conf.insert_json5("listeners", json.dumps(args.listener))
key = args.key

# zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---


def listener(sample):
    time = '(not specified)' if sample.source_info is None or sample.timestamp is None else datetime.fromtimestamp(
        sample.timestamp.time)
    print(">> [Subscriber] Received {} ('{}': '{}')"
          .format(sample.kind, sample.key_expr, sample.payload.decode("utf-8"), time))


# initiate logging
zenoh.init_logger()

print("Openning session...")
session = zenoh.open(conf)

print("Creating Subscriber on '{}'...".format(key))

sub = session.subscribe(key, listener, reliability=Reliability.Reliable, mode=SubMode.Push)

print("Enter 'q' to quit...")
c = '\0'
while c != 'q':
    c = sys.stdin.read(1)
    if c == '':
        time.sleep(1)
Beispiel #6
0
async def main():
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(prog='z_eval',
                                     description='zenoh eval example')
    parser.add_argument('--mode',
                        '-m',
                        dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument('--connect',
                        '-e',
                        dest='connect',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to connect to.')
    parser.add_argument('--listen',
                        '-l',
                        dest='listen',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to listen on.')
    parser.add_argument(
        '--key',
        '-k',
        dest='key',
        default='/demo/example/zenoh-python-eval',
        type=str,
        help='The key expression matching queries to evaluate.')
    parser.add_argument('--value',
                        '-v',
                        dest='value',
                        default='Eval from Python!',
                        type=str,
                        help='The value to reply to queries.')
    parser.add_argument('--config',
                        '-c',
                        dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else zenoh.Config()
    if args.mode is not None:
        conf.insert_json5(zenoh.config.MODE_KEY, json.dumps(args.mode))
    if args.connect is not None:
        conf.insert_json5(zenoh.config.CONNECT_KEY, json.dumps(args.connect))
    if args.listen is not None:
        conf.insert_json5(zenoh.config.LISTEN_KEY, json.dumps(args.listen))
    key = args.key
    value = args.value

    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---

    # Note: As an example the concrete implementation of the eval callback is implemented here as a coroutine.
    #       It checks if the query's value_selector (the substring after '?') is a float, and if yes, sleeps for this number of seconds.
    #       Run example/asyncio/z_get_parallel.py example to see how 3 concurrent get() are executed in parallel in this z_eval.py
    async def eval_corouting(query):
        selector = query.selector
        try:
            sleep_time = selector.parse_value_selector().properties.get(
                'sleep')
            if sleep_time is not None:
                print("  Sleeping {} secs before replying".format(
                    float(sleep_time)))
                await asyncio.sleep(float(sleep_time))
        except Exception as e:
            print("  WARN: error in value selector: {}. Ignore it.".format(e))
        print("  Replying to query on {}".format(selector))
        reply = "{} (this is the reply to query on {})".format(value, selector)
        query.reply(Sample(key_expr=key, payload=reply.encode()))

    async def eval_callback(query):
        print(">> [Queryable ] Received Query '{}'".format(query.selector))
        # schedule a task that will call eval_corouting(query)
        asyncio.create_task(eval_corouting(query))

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    session = await zenoh.async_open(conf)

    print("Creating Queryable on '{}'...".format(key))
    queryable = await session.queryable(key, eval_callback, kind=EVAL)

    print("Enter 'q' to quit......")
    c = '\0'
    while c != 'q':
        c = sys.stdin.read(1)
        if c == '':
            time.sleep(1)

    await queryable.close()
    await session.close()
Beispiel #7
0
async def main():
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(
        prog='z_get_parallel',
        description='zenoh parallel get example')
    parser.add_argument('--mode', '-m', dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument('--connect', '-e', dest='connect',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to connect to.')
    parser.add_argument('--listen', '-l', dest='listen',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to listen on.')
    parser.add_argument('--selector', '-s', dest='selector',
                        default='/demo/example/**',
                        type=str,
                        help='The selection of resources to query.')
    parser.add_argument('--kind', '-k', dest='kind',
                        choices=['ALL_KINDS', 'STORAGE', 'EVAL'],
                        default='ALL_KINDS',
                        type=str,
                        help='The KIND of queryables to query.')
    parser.add_argument('--target', '-t', dest='target',
                        choices=['ALL', 'BEST_MATCHING',
                                 'ALL_COMPLETE', 'NONE'],
                        default='ALL',
                        type=str,
                        help='The target queryables of the query.')
    parser.add_argument('--config', '-c', dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else zenoh.Config()
    if args.mode is not None:
        conf.insert_json5(zenoh.config.MODE_KEY, json.dumps(args.mode))
    if args.connect is not None:
        conf.insert_json5(zenoh.config.CONNECT_KEY, json.dumps(args.connect))
    if args.listen is not None:
        conf.insert_json5(zenoh.config.LISTEN_KEY, json.dumps(args.listen))
    selector = args.selector
    kind = {
        'ALL_KINDS': queryable.ALL_KINDS,
        'STORAGE': queryable.STORAGE,
        'EVAL': queryable.EVAL}.get(args.kind)
    target = {
        'ALL': Target.All(),
        'BEST_MATCHING': Target.BestMatching(),
        'ALL_COMPLETE': Target.AllComplete(),
        'NONE': Target.No()}.get(args.target)

    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    session = await zenoh.async_open(conf)

    async def do_query(sleep_time):
        print("Sending Query '{}?(sleep={})'...".format(selector, sleep_time))
        replies = await session.get("{}?(sleep={})".format(selector, sleep_time), target=QueryTarget(kind, target))
        for reply in replies:
            print(">> Received ('{}': '{}')"
                  .format(reply.sample.key_expr, reply.sample.payload.decode("utf-8")))

    start = time.time()
    await asyncio.gather(
        asyncio.create_task(do_query(1)),
        asyncio.create_task(do_query(2)),
        asyncio.create_task(do_query(3)),
    )
    end = time.time()
    print(f'Time: {end-start:.2f} sec')

    await session.close()
Beispiel #8
0
def main(stdscr):
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(prog='zn_sub',
                                     description='zenoh-net sub example')
    parser.add_argument('--mode',
                        '-m',
                        dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument(
        '--peer',
        '-e',
        dest='peer',
        metavar='LOCATOR',
        action='append',
        type=str,
        help='Peer locators used to initiate the zenoh session.')
    parser.add_argument('--listener',
                        '-l',
                        dest='listener',
                        metavar='LOCATOR',
                        action='append',
                        type=str,
                        help='Locators to listen on.')
    parser.add_argument('--config',
                        '-c',
                        dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')
    parser.add_argument('--cmd_vel',
                        dest='cmd_vel',
                        default='/rt/turtle1/cmd_vel',
                        type=str,
                        help='The "cmd_vel" ROS2 topic.')
    parser.add_argument('--rosout',
                        dest='rosout',
                        default='/rt/rosout',
                        type=str,
                        help='The "rosout" ROS2 topic.')
    parser.add_argument('--angular_scale',
                        '-a',
                        dest='angular_scale',
                        default='2.0',
                        type=float,
                        help='The angular scale.')
    parser.add_argument('--linear_scale',
                        '-x',
                        dest='linear_scale',
                        default='2.0',
                        type=float,
                        help='The linear scale.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else {}
    if args.mode is not None:
        conf["mode"] = args.mode
    if args.peer is not None:
        conf["peer"] = ",".join(args.peer)
    if args.listener is not None:
        conf["listener"] = ",".join(args.listener)
    cmd_vel = args.cmd_vel
    rosout = args.rosout
    angular_scale = args.angular_scale
    linear_scale = args.linear_scale

    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    z = Zenoh(conf)
    workspace = z.workspace()

    def rosout_callback(change):
        if change.value is not None:
            log = Log.deserialize(change.value.get_content())
            print('[{}.{}] [{}]: {}'.format(log.stamp.sec, log.stamp.nanosec,
                                            log.name, log.msg))

    print("Subscriber on '{}'...".format(rosout))
    sub = workspace.subscribe(rosout, rosout_callback)

    def pub_twist(linear, angular):
        print("Pub twist: {} - {}".format(linear, angular))
        t = Twist(linear=Vector3(x=linear, y=0.0, z=0.0),
                  angular=Vector3(x=0.0, y=0.0, z=angular))
        workspace.put(cmd_vel, t.serialize())

    while True:
        c = stdscr.getch()
        if c == curses.KEY_UP:
            pub_twist(1.0 * linear_scale, 0.0)
        elif c == curses.KEY_DOWN:
            pub_twist(-1.0 * linear_scale, 0.0)
        elif c == curses.KEY_LEFT:
            pub_twist(0.0, 1.0 * angular_scale)
        elif c == curses.KEY_RIGHT:
            pub_twist(0.0, -1.0 * angular_scale)
        elif c == 27 or c == ord('q'):
            break

    sub.close()
    zenoh.close()
Beispiel #9
0
async def main():
    # --- Command line argument parsing --- --- --- --- --- ---
    parser = argparse.ArgumentParser(prog='z_sub',
                                     description='zenoh sub example')
    parser.add_argument('--mode',
                        '-m',
                        dest='mode',
                        choices=['peer', 'client'],
                        type=str,
                        help='The zenoh session mode.')
    parser.add_argument('--connect',
                        '-e',
                        dest='connect',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to connect to.')
    parser.add_argument('--listen',
                        '-l',
                        dest='listen',
                        metavar='ENDPOINT',
                        action='append',
                        type=str,
                        help='Endpoints to listen on.')
    parser.add_argument('--key',
                        '-k',
                        dest='key',
                        default='/demo/example/**',
                        type=str,
                        help='The key expression to subscribe to.')
    parser.add_argument('--config',
                        '-c',
                        dest='config',
                        metavar='FILE',
                        type=str,
                        help='A configuration file.')

    args = parser.parse_args()
    conf = zenoh.config_from_file(
        args.config) if args.config is not None else zenoh.Config()
    if args.mode is not None:
        conf.insert_json5(zenoh.config.MODE_KEY, json.dumps(args.mode))
    if args.connect is not None:
        conf.insert_json5(zenoh.config.CONNECT_KEY, json.dumps(args.connect))
    if args.listen is not None:
        conf.insert_json5(zenoh.config.LISTEN_KEY, json.dumps(args.listen))
    key = args.key

    # zenoh-net code  --- --- --- --- --- --- --- --- --- --- ---
    async def listener(sample):
        print(">> [Subscriber] Received {} ('{}': '{}')".format(
            sample.kind, sample.key_expr, sample.payload.decode("utf-8")))

    # initiate logging
    zenoh.init_logger()

    print("Openning session...")
    session = await zenoh.async_open(conf)

    print("Creating Subscriber on '{}'...".format(key))

    sub = await session.subscribe(key,
                                  listener,
                                  reliability=Reliability.Reliable,
                                  mode=SubMode.Push)

    print("Enter 'q' to quit...")
    c = '\0'
    while c != 'q':
        c = sys.stdin.read(1)
        if c == '':
            time.sleep(1)

    await sub.close()
    await session.close()