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

        L.warning("[ZENOH] Openning session...")
        self.z_session = Zenoh(self.conf)

        L.warning("[ZENOH] Create New workspace...")
        self.workspace = self.z_session.workspace()
示例#2
0
 def test_create_delete_storage(self):
     y = Zenoh.login(ZSERVER)
     admin = y.admin()
     stid = '123'
     res1 = admin.add_storage(stid, {'selector': '/myzenoh/**'})
     time.sleep(1)  # TODO remove
     res2 = admin.remove_storage(stid)
     y.logout()
     self.assertTrue(res1)
     self.assertTrue(res2)
示例#3
0
 def test_create_delete_workspace(self):
     y = Zenoh.login(ZSERVER)
     admin = y.admin()
     stid = '123'
     admin.add_storage(stid, {'selector': '/myzenoh/**'})
     time.sleep(1)  # TODO remove
     workspace = y.workspace('/myzenoh')
     self.assertEqual(workspace.path, Path('/myzenoh'))
     admin.remove_storage(stid)
     y.logout()
示例#4
0
 def test_put_get_remove(self):
     y = Zenoh.login(ZSERVER)
     admin = y.admin()
     stid = '123'
     admin.add_storage(stid, {'selector': '/myzenoh/**'})
     time.sleep(1)  # TODO remove
     workspace = y.workspace('/myzenoh')
     d = Value('hello!', encoding=Encoding.STRING)
     self.assertTrue(workspace.put('/myzenoh/key1', d))
     data = workspace.get('/myzenoh/key1')[0]
     self.assertEqual(data.get_value(), d)
     self.assertEqual(data.get_path(), '/myzenoh/key1')
     self.assertTrue(workspace.remove('/myzenoh/key1'))
     self.assertEqual(workspace.get('/myzenoh/key1'), [])
     admin.remove_storage(stid)
     y.logout()
示例#5
0
    def test__big_put_get_remove(self):
        y = Zenoh.login('127.0.0.1')
        admin = y.admin()
        stid = '123'
        admin.add_storage(stid, {'selector': '/myzenoh/**'})
        time.sleep(1)  # TODO remove
        workspace = y.workspace('/myzenoh')

        for i in range(0, 100):
            v = 'x{}'.format(i) * 512
            workspace.put('/myzenoh/big/{}'.format(i),
                          Value(v, encoding=Encoding.STRING))

        dataset = workspace.get('/myzenoh/big/**')
        self.assertEqual(len(dataset), 100)
        admin.remove_storage(stid)
        y.logout()
示例#6
0
    def test_eval(self):
        y = Zenoh.login(ZSERVER)
        admin = y.admin()
        stid = '123'
        admin.add_storage(stid, {'selector': '/myzenoh/**'})
        time.sleep(1)  # TODO remove
        workspace = y.workspace('/myzenoh')

        def cb(path, args):
            return Value('{} World!'.format(args['hello']),
                         encoding=Encoding.STRING)

        workspace.register_eval('/myzenoh/key1', cb)
        dataset = workspace.get('/myzenoh/key1?(hello=mondo)')
        self.assertEqual(dataset[0].get_path(), '/myzenoh/key1')
        self.assertEqual(dataset[0].get_value(),
                         Value('mondo World!', encoding=Encoding.STRING))
        workspace.unregister_eval('/myzenoh/key1')
        admin.remove_storage(stid)
        y.logout()
示例#7
0
    def test_sub_remove(self):
        y = Zenoh.login(ZSERVER)
        admin = y.admin()
        stid = '123'
        admin.add_storage(stid, {'selector': '/myzenoh/**'})
        time.sleep(1)  # TODO remove
        workspace = y.workspace('/myzenoh')
        local_var = mvar.MVar()
        workspace.put('/myzenoh/key1', Value('123', encoding=Encoding.STRING))

        def cb(kvs):
            self.assertEqual(kvs[0].get_path(), '/myzenoh/key1')
            self.assertEqual(kvs[0].get_kind(), ChangeKind.REMOVE)
            local_var.put(kvs)

        sid = workspace.subscribe('/myzenoh/key1', cb)
        workspace.remove('/myzenoh/key1')
        self.assertTrue(workspace.unsubscribe(sid))
        admin.remove_storage(stid)
        y.logout()
示例#8
0
    def login(locator, properties=None):
        '''

        Establish a session with the Yaks instance reachable via provided
        Zenoh locator. If the provided locator is ``None``, :func:`login`
        will perform some dynamic discovery and try to establish the session
        automatically. When not ``None``, the locator must have the format:
        ``tcp/<ip>:<port>``.

        :param locator: a Zenoh locator or ``None``.
        :param properties: the Properties to be used for this session
            (e.g. "user", "password", ...). Can be ``None``.
        :returns: a Yaks object.

        '''
        zprops = {} if properties is None else {
            zenoh.Z_USER_KEY if k == "user" else zenoh.Z_PASSWORD_KEY: val
            for k, val in properties.items()
            if k == "user" or key == "password"
        }

        return Yaks(Zenoh.open(locator, zprops))
def main(address, selector):
    # client configuration
    conf = {
        'mode': 'client',
        'peer': '{}'.format(address),
    }

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

    print("New workspace...")
    workspace = zenoh.workspace()

    # getting the data from zenoh, it can come from a storage or an eval
    print("Get Data from '{}'...".format(selector))

    output_data = []
    for data in workspace.get(selector):
        _, _, m, s, n = data.path.split('/')
        m = int(m)
        s = int(s)
        n = int(n)
        output_entry = {
            'm': m,
            's': s,
            'n': n,
            'value': data.value.get_content(),
            'timestamp': data.timestamp
        }
        output_data.append(output_entry)

    sorted_output_data = sorted(output_data, key=lambda k: k['n'])

    for data in sorted_output_data:
        print(data)

    zenoh.close()
示例#10
0
# http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
#   ADLINK zenoh team, <*****@*****.**>

import sys
from zenoh import Zenoh, Selector, Path, Workspace, Encoding, Value

selector = '/demo/example/**'
if len(sys.argv) > 1:
    selector = sys.argv[1]

locator = None
if len(sys.argv) > 2:
    locator = sys.argv[2]

print('Login to Zenoh (locator={})...'.format(locator))
z = Zenoh.login(locator)

print('Use Workspace on "/"')
w = z.workspace('/')

print('Get from {}'.format(selector))
for data in w.get(selector):
    print('  {} : {}'.format(data.path, data.value))

z.logout()
示例#11
0
from zenoh import Zenoh

if __name__ == "__main__":
    z = Zenoh({})
    w = z.workspace('/')
    results = w.get('/myhome/kitcken/temp')
    key, value = results[0].path, results[0].value
    print('  {} : {}'.format(key, value))
示例#12
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()
示例#13
0
parser.add_argument('--selector', '-s', dest='selector',
                    default='/demo/example/**',
                    type=str,
                    help='The selection of resources to get.')

args = parser.parse_args()
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)
selector = args.selector

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

# initiate logging
zenoh.init_logger()

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

print("New workspace...")
workspace = zenoh.workspace()

print("Get Data from '{}'...".format(selector))
for data in workspace.get(selector):
    print('  {} : {}  (encoding: {} , timestamp: {})'.format(
        data.path, data.value.get_content(), data.value.encoding_descr(), data.timestamp))

zenoh.close()
示例#14
0
 def test_create_close_api(self):
     y = Zenoh.login(ZSERVER)
     self.assertTrue(y.rt.running)
     y.logout()
     self.assertFalse(y.rt.running)
示例#15
0
                                 description='Produces float values')
parser.add_argument('--path',
                    '-p',
                    dest='path',
                    default='/zenoh/examples/native/float',
                    type=str,
                    help='the path representing the float resource')

parser.add_argument(
    '--locator',
    '-l',
    dest='locator',
    default=None,
    type=str,
    help='The locator to be used to boostrap the zenoh session.'
    ' By default dynamic discovery is used')

args = parser.parse_args()

# zenoh code  --- --- --- --- --- --- --- --- --- --- ---
z = Zenoh.login(args.locator)
w = z.workspace()

while (True):
    v = input("Insert value (\'.\' to exit): ")
    if v != '.':
        w.put(args.path, float(v))
    else:
        z.logout()
        break
    if len(res) > 0 and res[0] == 'y':
        torch.save(
            global_model.state_dict(), 'global.pt'
        )  # be aware that this can overwrite a smarter model if this application is stopped and restarted
    else:
        global_model.load_state_dict(torch.load('global.pt'))
else:
    torch.save(
        global_model.state_dict(), 'global.pt'
    )  # be aware that this can overwrite a smarter model if this application is stopped and restarted

# initiate logging
zenoh.init_logger()

print("Opening session...")
z = Zenoh(conf)

print("New workspace...")
workspace = z.workspace()

# 0 - Put global model to a path where clients can get it
print("Put global model in /federated/nodes/global")
save_and_put_global_parameters(global_model.state_dict())

# 1 - Listen for notifications
notification_selector = selector + '/notifications'
print("Subscribed to '{}'...".format(notification_selector))
notification_subscriber = workspace.subscribe(notification_selector,
                                              notification_listener)

print("Press q to stop...")
class ZenohNative(ServiceABC):
    """
	A higher level API providing the same abstractions as the zenoh-net API in a simpler and more data-centric oriented
	manner as well as providing all the building blocks to create a distributed storage. The zenoh layer is aware of
	the data content and can apply content-based filtering and transcoding.
	(source: http://zenoh.io/docs/getting-started/key-concepts/)

	Available functionalities:
		[1] put         : push live data to the matching subscribers and storages. (equivalent of zenoh-net write)
		[2] subscribe   : subscriber to live data. (equivalent of zenoh-net subscribe)
		[3] get         : get data from the matching storages and evals. (equivalent of zenoh-net query)
		[4] storage     : the combination of a zenoh-net subscriber to listen for live data to store and a zenoh-net
						  queryable to reply to matching get requests.
		[5] eval        : an entity able to reply to get requests. Typically used to provide data on demand or
						  build a RPC system. (equivalent of zenoh-net queryable)

	Implemented scenarios:
	1. Zenoh SUBSCRIBER
		Sample input: listener=None, mode='peer', peer=None, selector='/demo2/**'
	2. Zenoh PUT
		Sample input: listener=None, mode='peer', path='/demo2/example/test', peer=None, value='Hello World'
	3. Zenoh GET
		Sample input: listener=None, mode='peer', peer=None, selector='/demo/example/**'
	"""
    class ZenohMode(Enum):
        PEER = "peer"
        CLIENT = "client"

    class SessionType(Enum):
        SUBSCRIBER = "SUBSCRIBER"
        PUT = "PUT"
        GET = "GET"

    def __init__(self,
                 _listener=None,
                 _mode="peer",
                 _peer=None,
                 _selector=None,
                 _path=None,
                 _session_type=None):
        super().__init__()
        self.listener = _listener  # Locators to listen on.
        self.mode = _mode  # The zenoh session mode.
        self.peer = _peer  # Peer locators used to initiate the zenoh session.
        self.selector = _selector  # The selection of resources to subscribe.
        self.path = _path  # The name of the resource to put.
        self.session_type = self._get_session_type(
            _session_type)  # Type of Zenoh connection

        # setup configuration
        self.conf = {"mode": self.mode}
        if self.peer is not None:
            self.conf["peer"] = self.peer
        if self.listener is not None:
            self.conf["listener"] = self.listener

        self.workspace = None
        self.z_session = None

        self.pub = None
        self.sub = None

    def _get_session_type(self, _type):
        if _type.upper() == self.SessionType.PUT.value:
            return self.SessionType.PUT.value
        elif _type.upper() == self.SessionType.SUBSCRIBER.value:
            return self.SessionType.SUBSCRIBER.value
        elif _type.upper() == self.SessionType.GET.value:
            return self.SessionType.GET.value
        else:
            return None

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

        L.warning("[ZENOH] Openning session...")
        self.z_session = Zenoh(self.conf)

        L.warning("[ZENOH] Create New workspace...")
        self.workspace = self.z_session.workspace()

    def close_connection(self, _subscriber=None):
        self.z_session.close()
        L.warning("[ZENOH] `{}` session has been closed".format(
            self.session_type))

    def register_subscriber(self, listener):
        L.warning("[ZENOH] Registering new consumer")
        self.sub = self.workspace.subscribe(self.selector, listener)

    def register_publisher(self):
        pass  # nothing to do here

    def publish_data(self, val):
        L.warning("[ZENOH] Publish data")
        self.workspace.put(self.path, val)
示例#18
0
if __name__ == "__main__":
    if len(sys.argv) < 5:
        print(
            "Usage <address of zenohd router> <rostopic> <rostopic hz> <replay secs>"
        )
    address = sys.argv[1]
    rostopic = sys.argv[2]
    sample_rate = int(sys.argv[3])
    duration = int(sys.argv[4])

    conf = {
        'mode': 'client',
        'peer': '{}'.format(address),
    }

    print("Opening Zenoh session...")
    zenoh = Zenoh(conf)
    print(
        "Server connected to Zenoh router {}, publishing on rostopic {}, at rate {}"
        .format(address, rostopic, sample_rate))
    # Zenoh workspace creation
    print("New Zenoh workspace...")
    workspace = zenoh.workspace(storage_path)

    app = create_app(workspace, rostopic, sample_rate, duration)
    app.register_blueprint(route_blueprint)
    app.run(host='0.0.0.0', port=5000, debug=True)

    # Shutting down Zenoh
    zenoh.close()
示例#19
0
def faces_listener(change):
    # print('[DEBUG] Received face to recognize: {}'.format(change.path))
    chunks = change.path.split('/')
    cam = chunks[-2]
    face = int(chunks[-1])

    if cam not in cams:
        cams[cam] = {}

    cams[cam][face] = bytes(change.value.get_content())


print('[INFO] Open zenoh session...')
zenoh.init_logger()
z = Zenoh(conf)
w = z.workspace()
time.sleep(0.5)

print('[INFO] Retrieve faces vectors...')
for vector in w.get(args['prefix'] + '/vectors/**'):
    add_face_to_data(data, vector.path, vector.value.get_content())

print('[INFO] Start recognition...')
sub1 = w.subscribe(args['prefix'] + '/vectors/**', update_face_data)
sub2 = w.subscribe(args['prefix'] + '/faces/*/*', faces_listener)

while True:
    for cam in list(cams):
        faces = cams[cam]
        for face in list(faces):