示例#1
0
 def test_json_value(self):
     d = {
         'this': 'is',
         'a': 'json value'
     }
     v = Value(d, encoding=Encoding.JSON)
     self.assertEqual(d, v.get_value())
     self.assertEqual(Encoding.JSON, v.encoding)
示例#2
0
        def cb(kvs):
            v = Value('123', encoding=Encoding.STRING)

            self.assertEqual(kvs[0].get_value(), v)
            self.assertEqual(kvs[0].get_path(), '/myzenoh/key1')
            self.assertEqual(kvs[0].get_kind(), ChangeKind.PUT)
            local_var.put(kvs)
示例#3
0
 def test_change(self):
     v1 = Value('test string value', encoding=Encoding.STRING)
     c = Change('/test', ChangeKind.PUT, None, v1)
     self.assertEqual('/test', c.get_path())
     self.assertEqual(ChangeKind.PUT, c.get_kind())
     self.assertEqual(v1, c.get_value())
     self.assertEqual(None, c.get_timestamp())
def save_and_put_global_parameters(dictionary):
    torch.save(dictionary, 'global_parameters.pt')
    print('>> [Save and Put] global_parameters.pt saved')

    f = open('global_parameters.pt', 'rb')
    binary = f.read()
    f.close()
    file_value = Value.Raw(zenoh.net.encoding.APP_OCTET_STREAM, binary)

    # --- send parameters with zenoh --- --- --- --- --- --- --- ---
    global_parameters_path = '/federated/global/parameters'
    print("Put global parameters into {}".format(global_parameters_path))
    workspace.put(global_parameters_path, file_value)
def send_parameters_to_all():
    global workspace

    f = open('global_parameters.pt', 'rb')
    binary = f.read()
    f.close()
    value = Value.Raw(zenoh.net.encoding.APP_OCTET_STREAM, binary)
    print('Parameters file loaded - zenoh.Value created and ready to be sent')

    # --- send parameters with zenoh --- --- --- --- --- --- --- ---
    for node_id in participants:
        global_node_path = selector + '/' + node_id + '/global_params'
        workspace.put(global_node_path,
                      value)  # /federated/nodes/<node_id>/global_params
        print(">> [Global params sender] global_params sent to {}".format(
            global_node_path))
示例#6
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()
示例#7
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()
示例#8
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()
示例#9
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()
示例#10
0
def eval_callback(path, properties):
    # In this Eval function, we choosed to get the name to be returned in the
    # StringValue in 3 possible ways, depending the properties specified in the
    # selector. For example, with the following selectors:
    #   - '/demo/example/zenoh-python-eval' :
    #         no properties are set, a default value is used for the name
    #   - '/demo/example/zenoh-python-eval?(name=Bob)' :
    #         'Bob' is used for the name
    #   - '/demo/example/zenoh-python-eval?(name=/demo/example/name)' :
    #         the Eval function does a GET on '/demo/example/name' and uses the
    #         1st result for the name
    print('>> Processing eval for path {} with properties: {}'.format(
        path, properties))
    # name = properties['name']
    name = properties.get('name', 'Zenoh Python!')

    if name.startswith('/'):
        print('   >> Get name to use from Zenoh at path: {}'.format(name))
        dataset = w.get(name)
        if len(dataset) > 0:
            name = dataset[0].value

    print('   >> Returning string: "Eval from {}"'.format(name))
    return Value('Eval from {}'.format(name), encoding=Encoding.STRING)
示例#11
0
    key = cv2.waitKey(1) & 0xFF
    if key == ord(' '):
        if len(rects) > 0:
            face = frame[rects[0][1]:rects[0][1] + rects[0][3],
                         rects[0][0]:rects[0][0] + rects[0][2]]
            box = [(rects[0][1], rects[0][0] + rects[0][2],
                    rects[0][1] + rects[0][3], rects[0][0])]
            encoding = face_recognition.face_encodings(rgb, box)[0]
            elist = encoding.tolist()

            faces = w.get(args['prefix'] + '/vectors/**')
            counter = 0
            for face in faces:
                chunks = face.path.split('/')
                name = chunks[-2]
                if name == args['name']:
                    if counter <= int(chunks[-1]):
                        counter = int(chunks[-1]) + 1

            uri = '{}/vectors/{}/{}'.format(args['prefix'], args['name'],
                                            str(counter))
            print('> Inserting face vector {}'.format(uri))
            w.put(uri, Value.Json(json.dumps(elist)))

    time.sleep(0.05)

    if key == ord('q'):
        exit(0)

z.close()
示例#12
0
 def test_not_equal(self):
     v1 = Value('test string value', encoding=Encoding.STRING)
     v2 = 'test string value'
     self.assertNotEqual(v1, v2)
示例#13
0
 def test_repr(self):
     v1 = Value('test string value', encoding=Encoding.STRING)
     v2 = 'test string value'
     self.assertEqual(repr(v1), v2)
示例#14
0
 def test_string_value(self):
     v = Value('test string value', encoding=Encoding.STRING)
     self.assertEqual('test string value', v.get_value())
     self.assertEqual(Encoding.STRING, v.encoding)
     self.assertEquals(Encoding.STRING, v.get_encoding())
示例#15
0
 def test_raw_value_bytes(self):
     iv = 'test raw value bytes'.encode()
     v = Value(iv)
     self.assertEqual(iv, v.get_value())
     self.assertEqual(Encoding.RAW, v.encoding)
示例#16
0
                    type=str,
                    help='Locators to listen on.')

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)
print(type(args.size))
size = args.size

# zenoh code  --- --- --- --- --- --- --- --- --- --- ---
print("Running throughput test for payload of {} bytes".format(size))
data = bytearray()
for i in range(0, size):
    data.append(i % 10)

v = Value.Raw(encoding.NONE, bytes(data))

print("New zenoh...")
zenoh = Zenoh(conf)

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


print('Press Ctrl-C to stop the publisher...')
while True:
    workspace.put('/test/thr', v)
示例#17
0
# Contributors:
#   ADLINK zenoh team, <*****@*****.**>

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

# If not specified as 1st argument, use a relative path
# (to the workspace below): 'zenoh-python-put'
path = 'zenoh-python-put'
if len(sys.argv) > 1:
    path = sys.argv[1]

value = 'Put from Zenoh Python!'
if len(sys.argv) > 2:
    value = sys.argv[2]

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

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

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

print('Put on {} : {}'.format(path, value))
w.put(path, Value(value, encoding=Encoding.STRING))

z.logout()
示例#18
0
import time
import sys
from zenoh import Zenoh, Selector, Path, Workspace, Encoding, Value
import argparse

locator = None
if len(sys.argv) < 2:
    print('USAGE:\n\tzn_put_thr <payload-size> [<zenoh-locator>]\n\n')
    sys.exit(-1)

length = int(sys.argv[1])
print("Running throughput test for payload of {} bytes".format(length))
if len(sys.argv) > 2:
    locator = sys.argv[2]

path = '/test/thr'

data = bytearray()
for i in range(0, length):
    data.append(i % 10)
v = Value(data, encoding=Encoding.RAW)

print('Login to Zenoh...')
z = Zenoh.login(locator)
print("Use Workspace on '/'")
w = z.workspace('/')

while True:
    w.put(path, v)
示例#19
0
 def cb(path, args):
     return Value('{} World!'.format(args['hello']),
                  encoding=Encoding.STRING)
示例#20
0
    ' By default dynamic discovery is used')

parser.add_argument('--path',
                    '-p',
                    dest='path',
                    default='/zenoh/examples/throughput/data',
                    type=str,
                    help='the resource used to write throughput data')

args = parser.parse_args()

locator = args.locator
size = args.size
path = args.path

# zenoh code  --- --- --- --- --- --- --- --- --- --- ---
print("Running throughput test for payload of {} bytes".format(size))
data = bytearray()
for i in range(0, size):
    data.append(i % 10)

v = Value(data)

print('Login to Zenoh...')
z = Zenoh.login(locator)
w = z.workspace()

print('Press Ctrl-C to stop the publisher...')
while True:
    w.put(path, v)
示例#21
0
 def test_raw_value_str(self):
     v = Value('test raw value')
     self.assertEqual('test raw value'.encode(), v.get_value())
     self.assertEqual(Encoding.RAW, v.encoding)
示例#22
0
        optimizer.step()

        running_loss += loss.item()
    else:
        print(f"Training loss: {running_loss/len(trainloader)}")

print('Model trained!')

torch.save(model.state_dict(), 'parameters.pt')

print('Model saved')

f = open('parameters.pt', 'rb')
bytes = f.read()
f.close
value = Value.Raw(zenoh.net.encoding.APP_OCTET_STREAM, bytes)

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

# initiate logging
zenoh.init_logger()

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

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

torch.save(model.state_dict(), './last.pt')
f = open('./last.pt')
示例#23
0
faces = json.load(f)

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

# If not yet existing, add a memory storage that will store the dataset
try:
    storage_admin_path = '/@/router/local/plugin/storages/backend/memory/storage/facerecog-store'
    if not w.get(storage_admin_path):
        path_expr = '{}/vectors/**'.format(args['prefix'])
        print('Add storage: on {}'.format(path_expr))
        properties = {'path_expr': path_expr}
        w.put(storage_admin_path, properties)
        time.sleep(1)
except:
    e = sys.exc_info()[0]
    print('Error creating storage: {}'.format(e))

for k, vs in faces.items():
    for j, v in enumerate(vs):
        uri = '{}/vectors/{}/{}'.format(args['prefix'], k, j)
        print('> Inserting face {}'.format(uri))
        w.put(uri, Value.Json(json.dumps(v)))

z.close()

print('[INFO] Done.')