rblidar.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import ctypes
  2. import logging
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. class point_data_t(ctypes.Structure):
  6. _pack_ = 1 # Set alignment to 1 byte
  7. _fields_ = [
  8. ("azimuth", ctypes.c_uint16),
  9. ("dist", ctypes.c_uint16),
  10. ("rssi", ctypes.c_uint16),
  11. ("timestamp", ctypes.c_uint32)
  12. ]
  13. # Create a corresponding numpy dtype for the structure
  14. point_dtype = np.dtype([
  15. ('azimuth', np.uint16),
  16. ('dist', np.uint16),
  17. ('rssi', np.uint16),
  18. ('timestamp', np.uint32)
  19. ])
  20. rblidar_lib = ctypes.CDLL('./rb_lidar.so')
  21. CALLBACK_TYPE = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int)
  22. class RBLidar:
  23. def __init__(self, ip: str, port: int, frame_callback=None):
  24. logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s')
  25. self.frame_callback = frame_callback
  26. self.callback = CALLBACK_TYPE(self._callback_wrapper)
  27. # Create the lidar instance
  28. self.lidar = rblidar_lib.rblidar_create(ip.encode('utf-8'), port, self.callback)
  29. def _callback_wrapper(self, data, length):
  30. # Convert the received data into a byte buffer
  31. byte_data = ctypes.string_at(data, length)
  32. # Create a NumPy array from the byte data
  33. point_data_array = np.frombuffer(byte_data, dtype=point_dtype)
  34. # If a NumPy callback is provided, call it
  35. if self.frame_callback is not None:
  36. self.frame_callback(point_data_array)
  37. def __del__(self):
  38. rblidar_lib.rblidar_destroy(self.lidar)
  39. if __name__ == "__main__":
  40. def my_frame_callback(point_data_array):
  41. for point in point_data_array:
  42. logging.info(f"Azimuth: {point['azimuth']}, Distance: {point['dist']}, RSSI: {point['rssi']}, Timestamp: {point['timestamp']}")
  43. lidar = RBLidar("192.168.8.1", 2368, frame_callback=my_frame_callback)
  44. try:
  45. while True:
  46. pass
  47. except KeyboardInterrupt:
  48. logging.info("Stopping...")