Esempio n. 1
0
    def dput(self, uri, value=None):
        data = self.get(uri)
        uri_values = ''
        if value is None:
            uri = uri.split('#')
            uri_values = uri[-1]
            uri = uri[0]
        if data is None or data == '':
            data = {}
        else:
            data = json.loads(data)

        if value is None:
            uri_values = uri_values.split('&')
            for tokens in uri_values:
                v = tokens.split('=')[-1]
                k = tokens.split('=')[0]
                d = self.dot2dict(k, v)
                data = self.data_merge(data, d)
        else:
            jvalues = json.loads(value)
            data = self.data_merge(data, jvalues)
        value = json.dumps(data)

        return self.workspace.put(Path(uri), Value(value))
Esempio n. 2
0
        def cb(kvs):
            v = Value('123', encoding=Encoding.STRING)

            self.assertEqual(kvs[0].get_value(), v)
            self.assertEqual(kvs[0].get_path(), '/myyaks/key1')
            self.assertEqual(kvs[0].get_kind(), ChangeKind.PUT)
            local_var.put(kvs)
Esempio n. 3
0
 def test_change(self):
     v1 = Value('test string value', encoding=Encoding.STRING)
     c = Change('/test', ChangeKind.PUT, 1234, v1)
     self.assertEqual('/test', c.get_path())
     self.assertEqual(ChangeKind.PUT, c.get_kind())
     self.assertEqual(v1, c.get_value())
     self.assertEqual(1234, c.get_time())
Esempio n. 4
0
 def test_put_get_remove(self):
     y = Yaks.login(YSERVER)
     admin = y.admin()
     stid = '123'
     admin.add_storage(stid, {'selector': '/myyaks/**'})
     time.sleep(1)  # TODO remove
     workspace = y.workspace('/myyaks')
     d = Value('hello!', encoding=Encoding.STRING)
     self.assertTrue(workspace.put('/myyaks/key1', d))
     entry = workspace.get('/myyaks/key1')[0]
     self.assertEqual(entry.get_value(), d)
     self.assertEqual(entry.get_path(), '/myyaks/key1')
     self.assertTrue(workspace.remove('/myyaks/key1'))
     self.assertEqual(workspace.get('/myyaks/key1'), [])
     admin.remove_storage(stid)
     y.logout()
Esempio n. 5
0
    def test__big_put_get_remove(self):
        y = Yaks.login('127.0.0.1')
        admin = y.admin()
        stid = '123'
        admin.add_storage(stid, {'selector': '/myyaks/**'})
        time.sleep(1)  # TODO remove
        workspace = y.workspace('/myyaks')

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

        entries = workspace.get('/myyaks/big/**')
        self.assertEqual(len(entries), 100)
        admin.remove_storage(stid)
        y.logout()
Esempio n. 6
0
    def test_sub_remove(self):
        y = Yaks.login(YSERVER)
        admin = y.admin()
        stid = '123'
        admin.add_storage(stid, {'selector': '/myyaks/**'})
        time.sleep(1)  # TODO remove
        workspace = y.workspace('/myyaks')
        local_var = mvar.MVar()
        workspace.put('/myyaks/key1', Value('123', encoding=Encoding.STRING))

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

        sid = workspace.subscribe('/myyaks/key1', cb)
        workspace.remove('/myyaks/key1')
        self.assertTrue(workspace.unsubscribe(sid))
        admin.remove_storage(stid)
        y.logout()
Esempio n. 7
0
    def test_eval(self):
        y = Yaks.login(YSERVER)
        admin = y.admin()
        stid = '123'
        admin.add_storage(stid, {'selector': '/myyaks/**'})
        time.sleep(1)  # TODO remove
        workspace = y.workspace('/myyaks')

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

        workspace.register_eval('/myyaks/key1', cb)
        entries = workspace.get('/myyaks/key1?(hello=mondo)')
        self.assertEqual(entries[0].get_path(), '/myyaks/key1')
        self.assertEqual(entries[0].get_value(),
                         Value('mondo World!', encoding=Encoding.STRING))
        workspace.unregister_eval('/myyaks/key1')
        admin.remove_storage(stid)
        y.logout()
Esempio n. 8
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/yaks-python-eval' :
    #         no properties are set, a default value is used for the name
    #   - '/demo/example/yaks-python-eval?(name=Bob)' :
    #         'Bob' is used for the name
    #   - '/demo/example/yaks-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', 'Yaks Python!')

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

    print('   >> Returning string: "Eval from {}"'.format(name))
    return Value('Eval from {}'.format(name), encoding=Encoding.STRING)
Esempio n. 9
0
                action='store_true',
                help="Disable the video display")
args = vars(ap.parse_args())

print("[INFO] Connecting to yaks...")
y = Yaks.login(args['yaks'])
ws = y.workspace('/')

print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)

while True:
    frame = vs.read()
    frame = imutils.resize(frame, width=args["width"])
    if not args['nodisplay']:
        cv2.imshow("PUB " + args['path'], frame)
    ret, jpeg = cv2.imencode('.jpg', frame,
                             [int(cv2.IMWRITE_JPEG_QUALITY), args["quality"]])
    buf = jpeg.tobytes()
    ws.put(args['path'], Value(buf, Encoding.RAW))

    time.sleep(args["delay"])
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

cv2.destroyAllWindows()
vs.stop()
z.close()
Esempio n. 10
0
            #print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))
        aq_sensor_value = grovepi.analogRead(aq_sensor)

        if aq_sensor_value > 700:
            #print ("High pollution")
            aq = "High pollution"
        elif aq_sensor_value > 300:
            #print ("Low pollution")
            aq = "Low pollution"
        else:
            #print ("Air fresh")
            aq = "Air fresh"
        #print("sensor_value =", aq_sensor_value)

        #print("sensor_value = %d resistance = %.2f" %(l_sensor_value,  resistance))
        d = {
            'distance': dist,
            'temperature': temp,
            'humidity': humidity,
            'air_quality_raw': aq_sensor_value,
            'air_quality': aq
        }
        print(json.dumps(d))
        ws.put(SENSOR_RESOURCE, Value(json.dumps(d), Encoding.STRING))
        time.sleep(1)

    except TypeError:
        print("Error")
    except IOError:
        print("Error")
Esempio n. 11
0
import time
import grovepi

period = 500000
ap = argparse.ArgumentParser()
ap.add_argument("-y",
                "--yaks",
                type=str,
                default="127.0.0.1",
                help="the YAKS instance")
ap.add_argument("-u", "--uri", required=True, help="the publication path")
ap.add_argument("-p", "--pin", required=True, help="GrovePi Pin")

args = vars(ap.parse_args())

pin = int(args['pin'])

y = Yaks.login(args['yaks'])
path = args['uri']
ws = y.workspace('/')

while True:
    try:
        value = grovepi.temp(pin, '1.2')
        print("value = {}".format(value))
        ws.put(path, Value(str(value), encoding=Encoding.STRING))
        time.sleep(.5)

    except IOError:
        print("Error")
Esempio n. 12
0
ap = argparse.ArgumentParser()
ap.add_argument("-z",
                "--zenoh",
                required=False,
                help="ip:port for the Zenoh router")

ap.add_argument("-s",
                "--samples",
                required=True,
                help="Samples to be sent as part of the test")

args = vars(ap.parse_args())
zlocator = args['zenoh']

samples = int(args['samples'])

y = Yaks.login(zlocator)
ws = y.workspace('/')

start = time.time()
path = '/ylatp/sample'
for i in range(0, samples):
    ws.put(path, Value('01234567', Encoding.STRING))
stop = time.time()
delta = stop - start

print("Sent {} samples in {}".format(samples, delta))
print("Throughput: {} msg/sec".format(samples / delta))
print("Average : {}".format(delta / samples))
Esempio n. 13
0
while True:
    raw = vs.read()
    frame = imutils.resize(raw, width=500)
    ratio = raw.shape[1] / 500

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    rects = detector.detectMultiScale(gray,
                                      scaleFactor=1.1,
                                      minNeighbors=5,
                                      minSize=(30, 30),
                                      flags=cv2.CASCADE_SCALE_IMAGE)
    boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects]

    faces = zip(range(len(boxes)), sorted(boxes))

    for (i, (top, right, bottom, left)) in faces:
        face = raw[int(top * ratio):int(bottom * ratio),
                   int(left * ratio):int(right * ratio)]
        face = imutils.resize(face, height=args["width"], width=args["width"])
        _, jpeg = cv2.imencode('.jpg', face, jpeg_opts)
        buf = jpeg.tobytes()

        ws.put("{}/faces/{}/{}".format(args['prefix'], pid, i),
               Value(buf, Encoding.RAW))

    time.sleep(args["delay"])

vs.stop()
y.logout()
Esempio n. 14
0
        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()

            fs = ws.get(args["prefix"] + "/vectors/**",
                        encoding=Encoding.STRING)
            counter = 0
            for k, _ in fs:
                chunks = k.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))
            ws.put(uri, Value(json.dumps(elist), encoding=Encoding.STRING))

    time.sleep(0.05)

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

vs.stop()
y.logout()
Esempio n. 15
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)
Esempio n. 16
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)
Esempio n. 17
0
 def test_not_equal(self):
     v1 = Value('test string value', encoding=Encoding.STRING)
     v2 = 'test string value'
     self.assertNotEqual(v1, v2)
Esempio n. 18
0
 def test_repr(self):
     v1 = Value('test string value', encoding=Encoding.STRING)
     v2 = 'test string value'
     self.assertEqual(repr(v1), v2)
Esempio n. 19
0
 def test_sql_value(self):
     sql = ['this', 'is', 'a', 'sql', 'value']
     v = Value(sql, encoding=Encoding.SQL)
     self.assertEqual(sql, v.get_value())
     self.assertEqual(Encoding.SQL, v.encoding)
Esempio n. 20
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)
Esempio n. 21
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())
Esempio n. 22
0
 def cb(path, args):
     return Value('{} World!'.format(args['hello']),
                  encoding=Encoding.STRING)
Esempio n. 23
0
print("[INFO] Starting recognition...")
ws.subscribe(args['prefix'] + "/vectors/**", update_face_data)
ws.subscribe(args['prefix'] + "/faces/*/*", faces_listener)

while True:
    for cam in list(cams):
        faces = cams[cam]
        for face in list(faces):
            npImage = np.array(faces[face])
            matImage = cv2.imdecode(npImage, 1)
            rgb = cv2.cvtColor(matImage, cv2.COLOR_BGR2RGB)

            encodings = face_recognition.face_encodings(rgb)

            name = "Unknown"
            if len(encodings) > 0:
                matches = face_recognition.compare_faces(
                    data["encodings"], encodings[0])
                if True in matches:
                    matchedIdxs = [i for (i, b) in enumerate(matches) if b]
                    counts = {}
                    for i in matchedIdxs:
                        name = data["names"][i]
                        counts[name] = counts.get(name, 0) + 1
                    name = max(counts, key=counts.get)

            path = args['prefix'] + "/faces/" + cam + "/" + str(face) + "/name"
            ws.put(path, Value(name, Encoding.STRING))

    time.sleep(args['delay'])
Esempio n. 24
0
import sys
from yaks import Yaks, Selector, Path, Workspace, Encoding, Value

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

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

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

print('Login to Yaks (locator={})...'.format(locator))
y = Yaks.login(locator)

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

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

y.logout()
Esempio n. 25
0
 def put(self, k, v):
     return self.workspace.put(Path(k), Value(v))