Skip to content
This repository was archived by the owner on Jul 22, 2020. It is now read-only.

Commit 6890700

Browse files
committed
Added ZException and Timestamp in zenoh.core package
1 parent 62954b7 commit 6890700

File tree

15 files changed

+124
-96
lines changed

15 files changed

+124
-96
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ dist:
2828

2929
clean:
3030
rm -rf ./build ./dist ./zenoh.egg-info .coverage;
31-
rm -rf zenoh_api.log .tox zenoh.egg-info ./zenoh/__pycache__/ ./zenoh/tests/__pycache__/;
31+
rm -rf zenoh_api.log .tox zenoh.egg-info ./zenoh/__pycache__/ ./zenoh/*/__pycache__/ ./zenoh/*/*/__pycache__/;
3232

3333
test:
3434
rm -rf ./tox

examples/zenoh-net/zn_sub.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55

66
def listener(rname, data, info):
7-
print(">> [Subscription listener] Received ('{}': '{}')"
8-
.format(rname, data.decode("utf-8")))
7+
print(">> [Subscription listener] Received ('{}': '{}') at {}"
8+
.format(rname, data.decode("utf-8"), info.tstamp))
99

1010

1111
if __name__ == '__main__':

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def read(fname):
1111
setup(
1212
name='zenoh',
1313
version='0.4.0',
14-
packages=['zenoh', 'zenoh.net'],
14+
packages=['zenoh', 'zenoh.net', 'zenoh.core'],
1515
author='kydos',
1616
description="Python client API for zenoh",
1717
long_description=read('README.md'),

zenoh/core/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
from .zexception import *
2+
from .timestamp import *

zenoh/core/timestamp.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from ctypes import *
2+
import datetime
3+
import binascii
4+
5+
6+
# Timestamp
7+
class Timestamp(Structure):
8+
_fields_ = [('clock_id', c_uint8 * 16),
9+
('time', c_size_t)]
10+
11+
def __hash__(self):
12+
return hash((self.time, self.clock_id[0], self.clock_id[1],
13+
self.clock_id[2], self.clock_id[3], self.clock_id[4],
14+
self.clock_id[5], self.clock_id[6], self.clock_id[7],
15+
self.clock_id[8], self.clock_id[9], self.clock_id[10],
16+
self.clock_id[11], self.clock_id[12], self.clock_id[13],
17+
self.clock_id[14], self.clock_id[15]))
18+
19+
def __eq__(self, other):
20+
if isinstance(other, self.__class__):
21+
if self.time != other.time:
22+
return False
23+
for i in range(0, 15):
24+
if self.clock_id[i] != other.clock_id[i]:
25+
return False
26+
return True
27+
28+
def __lt__(self, other):
29+
if self.time < other.time:
30+
return True
31+
if self.time > other.time:
32+
return False
33+
for i in range(0, 15):
34+
if self.clock_id[i] < other.clock_id[i]:
35+
return True
36+
if self.clock_id[i] > other.clock_id[i]:
37+
return False
38+
return False
39+
40+
def __str__(self):
41+
sec = self.time >> 32
42+
time = datetime.datetime.utcfromtimestamp(float(sec))
43+
frac = self.time & 0xffffffff
44+
ns = int((frac * 1000000000) / 0x100000000)
45+
id = binascii.hexlify(self.clock_id).decode("ascii")
46+
return "{}.{:09d}Z/{}".format(time.isoformat(), ns, id)
47+
48+
def floattime(self):
49+
"""
50+
Return the Timestamp's creation time as a float
51+
(i.e. number of seconds since Epoch: January 1, 1970, 00:00:00 (UTC))
52+
Warning: the time might be rounded, depending the float precision on
53+
your host.
54+
"""
55+
sec = self.time >> 32
56+
frac = self.time & 0xffffffff
57+
ns = float(frac) / 0x100000000
58+
return sec + ns
59+
60+
def datetime(self, tzinfo):
61+
"""
62+
Return the Timestamp's creation time as a datetime.datetime
63+
Warning: the time is rounded to milliseconds as datetime precision
64+
is millisecond.
65+
"""
66+
return datetime.datetime.fromtimestamp(self.floattime(), tzinfo)

zenoh/core/zexception.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class ZException(Exception):
2+
def __get_code_name(self, code):
3+
codes = {
4+
0x01: 'Z_VLE_PARSE_ERROR',
5+
0x02: 'Z_ARRAY_PARSE_ERROR',
6+
0x03: 'Z_STRING_PARSE_ERROR',
7+
0x81: 'ZN_PROPERTY_PARSE_ERROR',
8+
0x82: 'ZN_PROPERTIES_PARSE_ERROR',
9+
0x83: 'ZN_MESSAGE_PARSE_ERROR',
10+
0x84: 'ZN_INSUFFICIENT_IOBUF_SIZE',
11+
0x85: 'ZN_IO_ERROR',
12+
0x86: 'ZN_RESOURCE_DECL_ERROR',
13+
0x87: 'ZN_PAYLOAD_HEADER_PARSE_ERROR',
14+
0x89: 'ZN_TX_CONNECTION_ERROR',
15+
0x8a: 'ZN_INVALID_ADDRESS_ERROR',
16+
0x8b: 'ZN_FAILED_TO_OPEN_SESSION',
17+
0x8c: 'ZN_UNEXPECTED_MESSAGE'
18+
}
19+
return codes.get(code, 'UNKOWN_ERROR_CODE(' + str(code) + ')')
20+
21+
def __init__(self, message, code=0, cause=None):
22+
if code != 0:
23+
message += ' (error code: ' + self.__get_code_name(code) + ')'
24+
if cause is not None:
25+
message = message + '. Caused by: ' + cause.str()
26+
super().__init__(message)
27+
self.code = code
28+
self.cause = cause

zenoh/net/binding.py

Lines changed: 2 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import platform
22
import os
33
import ctypes
4-
import datetime
5-
import binascii
64
import traceback
75
from ctypes import *
86
from functools import partial
7+
from zenoh.core import Timestamp
98

109
ZN_INT_RES_KEY = 0
1110
ZN_STR_RES_KEY = 1
@@ -123,73 +122,10 @@ class zn_resource_key_t(Structure):
123122
_fields_ = [('kind', c_int), ('key', zn_res_key_t)]
124123

125124

126-
# TimeStamp
127-
class zn_timestamp_t(Structure):
128-
_fields_ = [('clock_id', c_uint8 * 16),
129-
('time', c_size_t)]
130-
131-
def __hash__(self):
132-
return hash((self.time, self.clock_id[0], self.clock_id[1],
133-
self.clock_id[2], self.clock_id[3], self.clock_id[4],
134-
self.clock_id[5], self.clock_id[6], self.clock_id[7],
135-
self.clock_id[8], self.clock_id[9], self.clock_id[10],
136-
self.clock_id[11], self.clock_id[12], self.clock_id[13],
137-
self.clock_id[14], self.clock_id[15]))
138-
139-
def __eq__(self, other):
140-
if isinstance(other, self.__class__):
141-
if self.time != other.time:
142-
return False
143-
for i in range(0, 15):
144-
if self.clock_id[i] != other.clock_id[i]:
145-
return False
146-
return True
147-
148-
def __lt__(self, other):
149-
if self.time < other.time:
150-
return True
151-
if self.time > other.time:
152-
return False
153-
for i in range(0, 15):
154-
if self.clock_id[i] < other.clock_id[i]:
155-
return True
156-
if self.clock_id[i] > other.clock_id[i]:
157-
return False
158-
return False
159-
160-
def __str__(self):
161-
sec = self.time >> 32
162-
time = datetime.datetime.utcfromtimestamp(float(sec))
163-
frac = self.time & 0xffffffff
164-
ns = int((frac * 1000000000) / 0x100000000)
165-
id = binascii.hexlify(self.clock_id).decode("ascii")
166-
return "{}.{:09d}Z/{}".format(time.isoformat(), ns, id)
167-
168-
def floattime(self):
169-
"""
170-
Return the Timestamp's creation time as a float
171-
(i.e. number of seconds since Epoch: January 1, 1970, 00:00:00 (UTC))
172-
Warning: the time might be rounded, depending the float precision on
173-
your host.
174-
"""
175-
sec = self.time >> 32
176-
frac = self.time & 0xffffffff
177-
ns = float(frac) / 0x100000000
178-
return sec + ns
179-
180-
def datetime(self, tzinfo):
181-
"""
182-
Return the Timestamp's creation time as a datetime.datetime
183-
Warning: the time is rounded to milliseconds as datetime precision
184-
is millisecond.
185-
"""
186-
return datetime.datetime.fromtimestamp(self.floattime(), tzinfo)
187-
188-
189125
# Data Info
190126
class zn_data_info_t(Structure):
191127
_fields_ = [('flags', c_uint),
192-
('tstamp', zn_timestamp_t),
128+
('tstamp', Timestamp),
193129
('encoding', c_uint8),
194130
('kind', c_ushort)]
195131

zenoh/net/session.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
from .binding import *
2+
import zenoh.core
3+
from zenoh.core import *
24
import socket
35
import time
46

@@ -107,8 +109,8 @@ def zn_to_canonical_locator(locator):
107109
if s == ':' and p != '':
108110
return ('tcp/' + socket.gethostbyname(h) + ':' + p).encode()
109111
else:
110-
raise Exception('Invalid locator format {}, it should be '
111-
'tcp/<ip-addr|host-name>:port'.format(locator))
112+
raise ZException('Invalid locator format {}, it should be '
113+
'tcp/<ip-addr|host-name>:port'.format(locator))
112114
elif b == '':
113115
h, s, p = locator.partition(':')
114116
if s == ':':
@@ -217,8 +219,7 @@ def __init__(self, locator, properties={}):
217219
self.session = r.value.session
218220
self.connected = True
219221
else:
220-
raise Exception('Unable to open zenoh session (error code: {}).'
221-
.format(r.value.error))
222+
raise ZException('Unable to open zenoh session', r.value.error)
222223

223224
self.zlib.zn_start_recv_loop(self.session)
224225
while not self.running:
@@ -269,7 +270,7 @@ def declare_publisher(self, res_name):
269270
if r.tag == 0:
270271
return r.value.pub
271272
else:
272-
raise Exception('Unable to create publisher')
273+
raise ZException('Unable to create publisher', r.value.error)
273274

274275
def declare_subscriber(self, selector, sub_mode, callback):
275276
"""
@@ -296,7 +297,7 @@ def declare_subscriber(self, selector, sub_mode, callback):
296297
return r.value.sub
297298
else:
298299
del subscriberCallbackMap[h]
299-
raise Exception('Unable to create subscriber')
300+
raise ZException('Unable to create subscriber', r.value.error)
300301

301302
def declare_storage(self, selector, subscriber_callback, query_handler):
302303
"""
@@ -330,7 +331,7 @@ def declare_storage(self, selector, subscriber_callback, query_handler):
330331
else:
331332
del subscriberCallbackMap[h]
332333
del replyCallbackMap[h]
333-
raise Exception('Unable to create storage')
334+
raise ZException('Unable to create storage', r.value.error)
334335

335336
def declare_eval(self, selector, query_handler):
336337
"""
@@ -359,7 +360,7 @@ def declare_eval(self, selector, query_handler):
359360
return r.value.eval
360361
else:
361362
del replyCallbackMap[h]
362-
raise Exception('Unable to create eval')
363+
raise ZException('Unable to create eval', r.value.error)
363364

364365
def stream_compact_data(self, pub, data):
365366
"""
@@ -452,7 +453,7 @@ def query(self, selector, predicate, callback,
452453
dest_evals.zn_qd)
453454
if r != 0:
454455
del replyCallbackMap[h]
455-
raise Exception('Unable to create query')
456+
raise ZException('Unable to create query', r)
456457

457458
def undeclare_publisher(self, pub):
458459
"""

zenoh/path.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,13 @@
1313
# Contributors: Gabriele Baldoni, ADLINK Technology Inc. - Zenoh API
1414

1515
import re
16-
from zenoh.exceptions import ValidationError
1716

1817

1918
class Path(object):
2019
def __init__(self, path):
2120
self.__path_regex = re.compile('^[^?#*]+$')
2221
if not self.is_valid(path):
23-
raise ValidationError("{} is not a valid Path".format(path))
22+
raise ValueError("Invalid Path: {}".format(path))
2423
self.path = path
2524

2625
@staticmethod

zenoh/selector.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# Contributors: Gabriele Baldoni, ADLINK Technology Inc. - Zenoh API
1414

1515
import re
16-
from zenoh.exceptions import ValidationError
1716
from zenoh.path import Path
1817

1918

@@ -22,8 +21,8 @@ def __init__(self, selector):
2221
self.__sel_regex = re.compile(
2322
'^([^?#]+)(\?([^\[()\]#]*)(\((.*)\))?)?(\#(.*))?$')
2423
if not self.is_valid(selector):
25-
raise ValidationError(
26-
"{} is not a valid Selector".format(selector))
24+
raise ValueError(
25+
"Invalid Selector: {}".format(selector))
2726
res = self.__sel_regex.match(selector)
2827
self.selector = selector
2928
self.path = res.group(1) or None

0 commit comments

Comments
 (0)