forked from SkoltechRobotics/rplidar
-
Notifications
You must be signed in to change notification settings - Fork 32
/
rplidar.py
488 lines (422 loc) · 17.3 KB
/
rplidar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
'''Simple and lightweight module for working with RPLidar rangefinder scanners.
Usage example:
>>> from rplidar import RPLidar
>>> lidar = RPLidar('/dev/ttyUSB0')
>>>
>>> info = lidar.get_info()
>>> print(info)
>>>
>>> health = lidar.get_health()
>>> print(health)
>>>
>>> for i, scan in enumerate(lidar.iter_scans()):
... print('%d: Got %d measures' % (i, len(scan)))
... if i > 10:
... break
...
>>> lidar.stop()
>>> lidar.stop_motor()
>>> lidar.disconnect()
For additional information please refer to the RPLidar class documentation.
'''
import logging
import sys
import time
import codecs
import serial
import struct
from collections import namedtuple
SYNC_BYTE = b'\xA5'
SYNC_BYTE2 = b'\x5A'
GET_INFO_BYTE = b'\x50'
GET_HEALTH_BYTE = b'\x52'
STOP_BYTE = b'\x25'
RESET_BYTE = b'\x40'
_SCAN_TYPE = {
'normal': {'byte': b'\x20', 'response': 129, 'size': 5},
'force': {'byte': b'\x21', 'response': 129, 'size': 5},
'express': {'byte': b'\x82', 'response': 130, 'size': 84},
}
DESCRIPTOR_LEN = 7
INFO_LEN = 20
HEALTH_LEN = 3
INFO_TYPE = 4
HEALTH_TYPE = 6
# Constants & Command to start A2 motor
MAX_MOTOR_PWM = 1023
DEFAULT_MOTOR_PWM = 660
SET_PWM_BYTE = b'\xF0'
_HEALTH_STATUSES = {
0: 'Good',
1: 'Warning',
2: 'Error',
}
class RPLidarException(Exception):
'''Basic exception class for RPLidar'''
def _b2i(byte):
'''Converts byte to integer (for Python 2 compatability)'''
return byte if int(sys.version[0]) == 3 else ord(byte)
def _showhex(signal):
'''Converts string bytes to hex representation (useful for debugging)'''
return [format(_b2i(b), '#02x') for b in signal]
def _process_scan(raw):
'''Processes input raw data and returns measurement data'''
new_scan = bool(_b2i(raw[0]) & 0b1)
inversed_new_scan = bool((_b2i(raw[0]) >> 1) & 0b1)
quality = _b2i(raw[0]) >> 2
if new_scan == inversed_new_scan:
raise RPLidarException('New scan flags mismatch')
check_bit = _b2i(raw[1]) & 0b1
if check_bit != 1:
raise RPLidarException('Check bit not equal to 1')
angle = ((_b2i(raw[1]) >> 1) + (_b2i(raw[2]) << 7)) / 64.
distance = (_b2i(raw[3]) + (_b2i(raw[4]) << 8)) / 4.
return new_scan, quality, angle, distance
def _process_express_scan(data, new_angle, trame):
new_scan = (new_angle < data.start_angle) & (trame == 1)
angle = (data.start_angle + (
(new_angle - data.start_angle) % 360
)/32*trame - data.angle[trame-1]) % 360
distance = data.distance[trame-1]
return new_scan, None, angle, distance
class RPLidar(object):
'''Class for communicating with RPLidar rangefinder scanners'''
def __init__(self, port, baudrate=115200, timeout=1, logger=None):
'''Initilize RPLidar object for communicating with the sensor.
Parameters
----------
port : str
Serial port name to which sensor is connected
baudrate : int, optional
Baudrate for serial connection (the default is 115200)
timeout : float, optional
Serial port connection timeout in seconds (the default is 1)
logger : logging.Logger instance, optional
Logger instance, if none is provided new instance is created
'''
self._serial = None
self.port = port
self.baudrate = baudrate
self.timeout = timeout
self._motor_speed = DEFAULT_MOTOR_PWM
self.scanning = [False, 0, 'normal']
self.express_trame = 32
self.express_data = False
self.motor_running = None
if logger is None:
logger = logging.getLogger('rplidar')
self.logger = logger
self.connect()
def connect(self):
'''Connects to the serial port with the name `self.port`. If it was
connected to another serial port disconnects from it first.'''
if self._serial is not None:
self.disconnect()
try:
self._serial = serial.Serial(
self.port, self.baudrate,
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
timeout=self.timeout)
except serial.SerialException as err:
raise RPLidarException('Failed to connect to the sensor '
'due to: %s' % err)
def disconnect(self):
'''Disconnects from the serial port'''
if self._serial is None:
return
self._serial.close()
def _set_pwm(self, pwm):
payload = struct.pack("<H", pwm)
self._send_payload_cmd(SET_PWM_BYTE, payload)
@property
def motor_speed(self):
return self._motor_speed
@motor_speed.setter
def motor_speed(self, pwm):
assert(0 <= pwm <= MAX_MOTOR_PWM)
self._motor_speed = pwm
if self.motor_running:
self._set_pwm(self._motor_speed)
def start_motor(self):
'''Starts sensor motor'''
self.logger.info('Starting motor')
# For A1
self._serial.setDTR(False)
# For A2
self._set_pwm(self._motor_speed)
self.motor_running = True
def stop_motor(self):
'''Stops sensor motor'''
self.logger.info('Stoping motor')
# For A2
self._set_pwm(0)
time.sleep(.001)
# For A1
self._serial.setDTR(True)
self.motor_running = False
def _send_payload_cmd(self, cmd, payload):
'''Sends `cmd` command with `payload` to the sensor'''
size = struct.pack('B', len(payload))
req = SYNC_BYTE + cmd + size + payload
checksum = 0
for v in struct.unpack('B'*len(req), req):
checksum ^= v
req += struct.pack('B', checksum)
self._serial.write(req)
self.logger.debug('Command sent: %s' % _showhex(req))
def _send_cmd(self, cmd):
'''Sends `cmd` command to the sensor'''
req = SYNC_BYTE + cmd
self._serial.write(req)
self.logger.debug('Command sent: %s' % _showhex(req))
def _read_descriptor(self):
'''Reads descriptor packet'''
descriptor = self._serial.read(DESCRIPTOR_LEN)
self.logger.debug('Received descriptor: %s', _showhex(descriptor))
if len(descriptor) != DESCRIPTOR_LEN:
raise RPLidarException('Descriptor length mismatch')
elif not descriptor.startswith(SYNC_BYTE + SYNC_BYTE2):
raise RPLidarException('Incorrect descriptor starting bytes')
is_single = _b2i(descriptor[-2]) == 0
return _b2i(descriptor[2]), is_single, _b2i(descriptor[-1])
def _read_response(self, dsize):
'''Reads response packet with length of `dsize` bytes'''
self.logger.debug('Trying to read response: %d bytes', dsize)
while self._serial.inWaiting() < dsize:
time.sleep(0.001)
data = self._serial.read(dsize)
self.logger.debug('Received data: %s', _showhex(data))
return data
def get_info(self):
'''Get device information
Returns
-------
dict
Dictionary with the sensor information
'''
if self._serial.inWaiting() > 0:
return ('Data in buffer, you can\'t have info ! '
'Run clean_input() to emptied the buffer.')
self._send_cmd(GET_INFO_BYTE)
dsize, is_single, dtype = self._read_descriptor()
if dsize != INFO_LEN:
raise RPLidarException('Wrong get_info reply length')
if not is_single:
raise RPLidarException('Not a single response mode')
if dtype != INFO_TYPE:
raise RPLidarException('Wrong response data type')
raw = self._read_response(dsize)
serialnumber = codecs.encode(raw[4:], 'hex').upper()
serialnumber = codecs.decode(serialnumber, 'ascii')
data = {
'model': _b2i(raw[0]),
'firmware': (_b2i(raw[2]), _b2i(raw[1])),
'hardware': _b2i(raw[3]),
'serialnumber': serialnumber,
}
return data
def get_health(self):
'''Get device health state. When the core system detects some
potential risk that may cause hardware failure in the future,
the returned status value will be 'Warning'. But sensor can still work
as normal. When sensor is in the Protection Stop state, the returned
status value will be 'Error'. In case of warning or error statuses
non-zero error code will be returned.
Returns
-------
status : str
'Good', 'Warning' or 'Error' statuses
error_code : int
The related error code that caused a warning/error.
'''
if self._serial.inWaiting() > 0:
return ('Data in buffer, you can\'t have info ! '
'Run clean_input() to emptied the buffer.')
self.logger.info('Asking for health')
self._send_cmd(GET_HEALTH_BYTE)
dsize, is_single, dtype = self._read_descriptor()
if dsize != HEALTH_LEN:
raise RPLidarException('Wrong get_info reply length')
if not is_single:
raise RPLidarException('Not a single response mode')
if dtype != HEALTH_TYPE:
raise RPLidarException('Wrong response data type')
raw = self._read_response(dsize)
status = _HEALTH_STATUSES[_b2i(raw[0])]
error_code = (_b2i(raw[1]) << 8) + _b2i(raw[2])
return status, error_code
def clean_input(self):
'''Clean input buffer by reading all available data'''
if self.scanning[0]:
return 'Cleanning not allowed during scanning process active !'
self._serial.flushInput()
self.express_trame = 32
self.express_data = False
def stop(self):
'''Stops scanning process, disables laser diode and the measurement
system, moves sensor to the idle state.'''
self.logger.info('Stopping scanning')
self._send_cmd(STOP_BYTE)
time.sleep(.1)
self.scanning[0] = False
self.clean_input()
def start(self, scan_type='normal'):
'''Start the scanning process
Parameters
----------
scan : normal, force or express.
'''
if self.scanning[0]:
return 'Scanning already running !'
'''Start the scanning process, enable laser diode and the
measurement system'''
status, error_code = self.get_health()
self.logger.debug('Health status: %s [%d]', status, error_code)
if status == _HEALTH_STATUSES[2]:
self.logger.warning('Trying to reset sensor due to the error. '
'Error code: %d', error_code)
self.reset()
status, error_code = self.get_health()
if status == _HEALTH_STATUSES[2]:
raise RPLidarException('RPLidar hardware failure. '
'Error code: %d' % error_code)
elif status == _HEALTH_STATUSES[1]:
self.logger.warning('Warning sensor status detected! '
'Error code: %d', error_code)
cmd = _SCAN_TYPE[scan_type]['byte']
self.logger.info('starting scan process in %s mode' % scan_type)
if scan_type == 'express':
self._send_payload_cmd(cmd, b'\x00\x00\x00\x00\x00')
else:
self._send_cmd(cmd)
dsize, is_single, dtype = self._read_descriptor()
if dsize != _SCAN_TYPE[scan_type]['size']:
raise RPLidarException('Wrong get_info reply length')
if is_single:
raise RPLidarException('Not a multiple response mode')
if dtype != _SCAN_TYPE[scan_type]['response']:
raise RPLidarException('Wrong response data type')
self.scanning = [True, dsize, scan_type]
def reset(self):
'''Resets sensor core, reverting it to a similar state as it has
just been powered up.'''
self.logger.info('Reseting the sensor')
self._send_cmd(RESET_BYTE)
time.sleep(2)
self.clean_input()
def iter_measures(self, scan_type='normal', max_buf_meas=3000):
'''Iterate over measures. Note that consumer must be fast enough,
otherwise data will be accumulated inside buffer and consumer will get
data with increasing lag.
Parameters
----------
max_buf_meas : int or False if you want unlimited buffer
Maximum number of bytes to be stored inside the buffer. Once
numbe exceeds this limit buffer will be emptied out.
Yields
------
new_scan : bool
True if measures belongs to a new scan
quality : int
Reflected laser pulse strength
angle : float
The measure heading angle in degree unit [0, 360)
distance : float
Measured object distance related to the sensor's rotation center.
In millimeter unit. Set to 0 when measure is invalid.
'''
self.start_motor()
if not self.scanning[0]:
self.start(scan_type)
while True:
dsize = self.scanning[1]
if max_buf_meas:
data_in_buf = self._serial.inWaiting()
if data_in_buf > max_buf_meas:
self.logger.warning(
'Too many bytes in the input buffer: %d/%d. '
'Cleaning buffer...',
data_in_buf, max_buf_meas)
self.stop()
self.start(self.scanning[2])
if self.scanning[2] == 'normal':
raw = self._read_response(dsize)
yield _process_scan(raw)
if self.scanning[2] == 'express':
if self.express_trame == 32:
self.express_trame = 0
if not self.express_data:
self.logger.debug('reading first time bytes')
self.express_data = ExpressPacket.from_string(
self._read_response(dsize))
self.express_old_data = self.express_data
self.logger.debug('set old_data with start_angle %f',
self.express_old_data.start_angle)
self.express_data = ExpressPacket.from_string(
self._read_response(dsize))
self.logger.debug('set new_data with start_angle %f',
self.express_data.start_angle)
self.express_trame += 1
self.logger.debug('process scan of frame %d with angle : '
'%f and angle new : %f', self.express_trame,
self.express_old_data.start_angle,
self.express_data.start_angle)
yield _process_express_scan(self.express_old_data,
self.express_data.start_angle,
self.express_trame)
def iter_scans(self, scan_type='normal', max_buf_meas=3000, min_len=5):
'''Iterate over scans. Note that consumer must be fast enough,
otherwise data will be accumulated inside buffer and consumer will get
data with increasing lag.
Parameters
----------
max_buf_meas : int
Maximum number of measures to be stored inside the buffer. Once
numbe exceeds this limit buffer will be emptied out.
min_len : int
Minimum number of measures in the scan for it to be yelded.
Yields
------
scan : list
List of the measures. Each measurment is tuple with following
format: (quality, angle, distance). For values description please
refer to `iter_measures` method's documentation.
'''
scan_list = []
iterator = self.iter_measures(scan_type, max_buf_meas)
for new_scan, quality, angle, distance in iterator:
if new_scan:
if len(scan_list) > min_len:
yield scan_list
scan_list = []
if distance > 0:
scan_list.append((quality, angle, distance))
class ExpressPacket(namedtuple('express_packet',
'distance angle new_scan start_angle')):
sync1 = 0xa
sync2 = 0x5
sign = {0: 1, 1: -1}
@classmethod
def from_string(cls, data):
packet = bytearray(data)
if (packet[0] >> 4) != cls.sync1 or (packet[1] >> 4) != cls.sync2:
raise ValueError('try to parse corrupted data ({})'.format(packet))
checksum = 0
for b in packet[2:]:
checksum ^= b
if checksum != (packet[0] & 0b00001111) + ((
packet[1] & 0b00001111) << 4):
raise ValueError('Invalid checksum ({})'.format(packet))
new_scan = packet[3] >> 7
start_angle = (packet[2] + ((packet[3] & 0b01111111) << 8)) / 64
d = a = ()
for i in range(0,80,5):
d += ((packet[i+4] >> 2) + (packet[i+5] << 6),)
a += (((packet[i+8] & 0b00001111) + ((
packet[i+4] & 0b00000001) << 4))/8*cls.sign[(
packet[i+4] & 0b00000010) >> 1],)
d += ((packet[i+6] >> 2) + (packet[i+7] << 6),)
a += (((packet[i+8] >> 4) + (
(packet[i+6] & 0b00000001) << 4))/8*cls.sign[(
packet[i+6] & 0b00000010) >> 1],)
return cls(d, a, new_scan, start_angle)