Skip to content

Commit 5e13b01

Browse files
committed
fix lidar JSON encoding
1 parent e063a74 commit 5e13b01

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

arenarobot/service/sensor/vl53l5cx.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@
1111
"""
1212

1313
import time
14+
from json import dumps, loads
1415
from typing import Sequence
1516

1617
import numpy as np
1718
from periphery import GPIO
1819

1920
from arenarobot.service.sensor import ArenaRobotServiceSensor
2021
from vl53l5cx_py.driver import VL53L5CX
22+
from vl53l5cx_py.helpers import VL53L5CXJSONEncoder
2123

2224

2325
class ArenaRobotServiceSensorVL53L5CX(ArenaRobotServiceSensor):
@@ -81,9 +83,6 @@ def fetch(self):
8183
data = []
8284
for sensor in self.sensors:
8385
ranges = sensor.get_range()
84-
# Remove byte-type data (not JSON-serializable)
85-
del ranges["nb_target_detected"]
86-
del ranges["reflectance"]
87-
del ranges["target_status"]
8886
data.append(ranges)
87+
data = loads(dumps(data, cls=VL53L5CXJSONEncoder))
8988
self.publish({"data": data})

vl53l5cx_py/cython/vl53l5cx_py_wrapper.pyx

+2-1
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,8 @@ cdef class VL53L5CX:
128128
cdef int32_t status = vl53l5cx_py_get_range(&self.dev_conf, &results)
129129
if status != 0:
130130
raise RuntimeError
131+
131132
return VL53L5CXSensorData(
132133
distance_mm=results.distance_mm,
133-
target_status=results.target_status
134+
target_status=np.frombuffer(results.target_status, dtype='S1')
134135
)

vl53l5cx_py/helpers.py

+17
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"""
1212

1313
from dataclasses import dataclass
14+
from json import JSONEncoder
1415
from typing import List
1516

1617
import numpy as np
@@ -41,3 +42,19 @@ class VL53L5CXSensorData():
4142
# 203.20,210.96,225.00,251.55,288.45,315.00,329.04,336.80,
4243
# 215.40,225.00,239.04,258.69,281.31,300.96,315.00,324.60,
4344
# 225.00,234.60,246.80,261.87,278.13,293.20,305.40,315.00]
45+
46+
class VL53L5CXJSONEncoder(JSONEncoder):
47+
"""JSON Encoder helper for VL53L5CX packets."""
48+
49+
def default(self, obj):
50+
"""JSON Encoder helper function for VL53L5CX packets."""
51+
if isinstance(obj, np.ndarray):
52+
return obj.tolist()
53+
54+
elif isinstance(obj, bytes):
55+
return int.from_bytes(obj, "little")
56+
57+
elif isinstance(obj, VL53L5CXSensorData):
58+
return vars(obj)
59+
60+
return JSONEncoder.default(self, obj)

0 commit comments

Comments
 (0)