Skip to content

Commit 7e8b9f6

Browse files
authored
Improve Python serialization (#11)
1 parent 2f39668 commit 7e8b9f6

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed

python/cli/visualization/serialization.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,41 @@
33
"""
44

55
# Needed when SLAM is disabled (no final map flag to indicate end of data)
6-
EXIT_AFTER_NO_DATA_FOR_N_SECONDS = 5
6+
HEADER_TIMEOUT = 5
7+
HEADER_SIZE = 16
78

89
import struct
910
import json
1011
import numpy as np
1112
import spectacularAI
1213
import time
1314

15+
def read_bytes(in_stream, n, timeout=0):
16+
dt = 0
17+
result = b"" # Initialize an empty bytes object
18+
while n > 0:
19+
chunk = in_stream.read(n)
20+
if len(chunk) > 0:
21+
result += chunk
22+
n -= len(chunk)
23+
else:
24+
time.sleep(0.01)
25+
dt += 0.01
26+
if timeout > 0 and dt > timeout: return False
27+
return result
28+
1429
def input_stream_reader(in_stream):
1530
MAGIC_BYTES = 2727221974
1631
shouldQuit = False
17-
exitCounter = 0
1832

1933
while not shouldQuit:
20-
messageHeader = in_stream.read(16)
21-
22-
if len(messageHeader) == 0:
23-
time.sleep(0.01)
24-
exitCounter += 0.01
25-
shouldQuit = exitCounter >= EXIT_AFTER_NO_DATA_FOR_N_SECONDS
26-
continue
27-
exitCounter = 0
34+
messageHeader = read_bytes(in_stream, HEADER_SIZE, HEADER_TIMEOUT)
35+
if messageHeader is False: break
2836

2937
magicBytes, messageId, jsonSize, binarySize = struct.unpack('@4I', messageHeader)
3038
if magicBytes != MAGIC_BYTES:
3139
raise Exception(f"Wrong magic bytes! Expected {MAGIC_BYTES} and received {magicBytes}")
32-
json_output = json.loads(in_stream.read(jsonSize).decode('ascii'))
40+
json_output = json.loads(read_bytes(in_stream, jsonSize).decode('ascii'))
3341

3442
if 'cameraPoses' in json_output: # Vio output
3543
assert(binarySize == 0)
@@ -41,13 +49,13 @@ def input_stream_reader(in_stream):
4149
if "pointCloud" in keyFrame:
4250
pointCloud = keyFrame["pointCloud"]
4351
points = pointCloud["size"]
44-
pointCloud["positionData"] = np.frombuffer(in_stream.read(points * 4 * 3), dtype=np.float32)
52+
pointCloud["positionData"] = np.frombuffer(read_bytes(in_stream, points * 4 * 3), dtype=np.float32)
4553
pointCloud["positionData"].shape = (points, 3)
4654
if pointCloud["hasNormals"]:
47-
pointCloud["normalData"] = np.frombuffer(in_stream.read(points * 4 * 3), dtype=np.float32)
55+
pointCloud["normalData"] = np.frombuffer(read_bytes(in_stream, points * 4 * 3), dtype=np.float32)
4856
pointCloud["normalData"].shape = (points, 3)
4957
if pointCloud["hasColors"]:
50-
pointCloud["rgb24Data"] = np.frombuffer(in_stream.read(points * 3), dtype=np.ubyte)
58+
pointCloud["rgb24Data"] = np.frombuffer(read_bytes(in_stream, points * 3), dtype=np.ubyte)
5159
pointCloud["rgb24Data"].shape = (points, 3)
5260
yield json_output
5361

0 commit comments

Comments
 (0)