forked from ideasxiang/r2auto_nav
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathr3auto_nav.py
More file actions
398 lines (346 loc) · 14.9 KB
/
Copy pathr3auto_nav.py
File metadata and controls
398 lines (346 loc) · 14.9 KB
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
# Copyright 2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import rclpy
from rclpy.node import Node
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from rclpy.qos import qos_profile_sensor_data
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import OccupancyGrid
import numpy as np
import math
import cmath
import time
import random
# constants
rotatechange = 0.5
speedchange = 0.1
occ_bins = [-1, 0, 100, 101]
stop_distance = 0.5
max_distance = 1.2
front_angle = 30
front_angles = range(-front_angle, front_angle + 1, 1)
scanfile = 'lidar.txt'
mapfile = 'map.txt'
msgfile = 'msg.txt'
# code from https://automaticaddison.com/how-to-convert-a-quaternion-into-euler-angles-in-python/
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around y in radians (counterclockwise)
yaw is rotation around z in radians (counterclockwise)
"""
t0 = +2.0 * (w * x + y * z)
t1 = +1.0 - 2.0 * (x * x + y * y)
roll_x = math.atan2(t0, t1)
t2 = +2.0 * (w * y - z * x)
t2 = +1.0 if t2 > +1.0 else t2
t2 = -1.0 if t2 < -1.0 else t2
pitch_y = math.asin(t2)
t3 = +2.0 * (w * z + x * y)
t4 = +1.0 - 2.0 * (y * y + z * z)
yaw_z = math.atan2(t3, t4)
return roll_x, pitch_y, yaw_z # in radians
class AutoNav(Node):
def __init__(self):
super().__init__('auto_nav')
# create publisher for moving TurtleBot
self.publisher_ = self.create_publisher(Twist, 'cmd_vel', 10)
self.get_logger().info('Created publisher')
# create subscription to track orientation
self.odom_subscription = self.create_subscription(
Odometry,
'odom',
self.odom_callback,
10)
self.get_logger().info('Created subscriber')
self.odom_subscription # prevent unused variable warning
# initialize variables
self.roll = 0
self.pitch = 0
self.yaw = 0
self.x = 0
self.y = 0
self.why_stop = 0
self.turn_already = 0
# create subscription to track occupancy
self.occ_subscription = self.create_subscription(
OccupancyGrid,
'map',
self.occ_callback,
qos_profile_sensor_data)
self.occ_subscription # prevent unused variable warning
self.occdata = np.array([])
# create subscription to track lidar
self.scan_subscription = self.create_subscription(
LaserScan,
'scan',
self.scan_callback,
qos_profile_sensor_data)
self.scan_subscription # prevent unused variable warning
self.laser_range = np.array([])
def odom_callback(self, msg):
# self.get_logger().info('In odom_callback')
orientation_quat = msg.pose.pose.orientation
self.roll, self.pitch, self.yaw = euler_from_quaternion(orientation_quat.x, orientation_quat.y,
orientation_quat.z, orientation_quat.w)
self.x = msg.pose.pose.position.x
self.y = msg.pose.pose.position.y
# self.get_logger().info('x: %f, y: %f' % (self.x, self.y))
# self.get_logger().info(str(msg))
# np.savetxt(msgfile, msg)
def occ_callback(self, msg):
# self.get_logger().info('In occ_callback')
# create numpy array
msgdata = np.array(msg.data)
# compute histogram to identify percent of bins with -1
# occ_counts = np.histogram(msgdata,occ_bins)
# calculate total number of bins
# total_bins = msg.info.width * msg.info.height
# log the info
# self.get_logger().info('Unmapped: %i Unoccupied: %i Occupied: %i Total: %i' % (occ_counts[0][0], occ_counts[0][1], occ_counts[0][2], total_bins))
# make msgdata go from 0 instead of -1, reshape into 2D
oc2 = msgdata + 1
# reshape to 2D array using column order
# self.occdata = np.uint8(oc2.reshape(msg.info.height,msg.info.width,order='F'))
self.occdata = np.uint8(oc2.reshape(msg.info.height, msg.info.width))
# self.get_logger().info(str(self.occdata))
# print to file
np.savetxt(mapfile, self.occdata)
def scan_callback(self, msg):
# self.get_logger().info('In scan_callback')
# create numpy array
self.laser_range = np.array(msg.ranges)
# print to file
# np.savetxt(scanfile, self.laser_range)
# replace 0's with nan
self.laser_range[self.laser_range == 0] = np.nan
# function to rotate the TurtleBot
def rotatebot(self, rot_angle):
self.get_logger().info('In rotatebot')
# create Twist object
twist = Twist()
# get current yaw angle
current_yaw = self.yaw
# log the info
self.get_logger().info('Current: %f' % math.degrees(current_yaw))
# we are going to use complex numbers to avoid problems when the angles go from
# 360 to 0, or from -180 to 180
c_yaw = complex(math.cos(current_yaw), math.sin(current_yaw))
# calculate desired yaw
target_yaw = current_yaw + math.radians(rot_angle)
# convert to complex notation
c_target_yaw = complex(math.cos(target_yaw), math.sin(target_yaw))
self.get_logger().info('Desired: %f' % math.degrees(cmath.phase(c_target_yaw)))
# divide the two complex numbers to get the change in direction
c_change = c_target_yaw / c_yaw
# get the sign of the imaginary component to figure out which way we have to turn
c_change_dir = np.sign(c_change.imag)
# set linear speed to zero so the TurtleBot rotates on the spot
twist.linear.x = 0.0
# set the direction to rotate
twist.angular.z = c_change_dir * rotatechange
# start rotation
self.publisher_.publish(twist)
# we will use the c_dir_diff variable to see if we can stop rotating
c_dir_diff = c_change_dir
# self.get_logger().info('c_change_dir: %f c_dir_diff: %f' % (c_change_dir, c_dir_diff))
# if the rotation direction was 1.0, then we will want to stop when the c_dir_diff
# becomes -1.0, and vice versa
while (c_change_dir * c_dir_diff > 0):
# allow the callback functions to run
rclpy.spin_once(self)
current_yaw = self.yaw
# convert the current yaw to complex form
c_yaw = complex(math.cos(current_yaw), math.sin(current_yaw))
# self.get_logger().info('Current Yaw: %f' % math.degrees(current_yaw))
# get difference in angle between current and target
c_change = c_target_yaw / c_yaw
# get the sign to see if we can stop
c_dir_diff = np.sign(c_change.imag)
# self.get_logger().info('c_change_dir: %f c_dir_diff: %f' % (c_change_dir, c_dir_diff))
self.get_logger().info('End Yaw: %f' % math.degrees(current_yaw))
# set the rotation speed to 0
twist.angular.z = 0.0
# stop the rotation
self.publisher_.publish(twist)
def pick_direction(self):
self.get_logger().info('In pick_direction')
if self.laser_range.size != 0:
# use nanargmax as there are nan's in laser_range added to replace 0's
# if 0 <= int(self.x) < len(past_angles) and 0 <= int(self.y) < len(past_angles[0]):
# if np.nanargmax(self.laser_range) not in past_angles[int(self.x)][int(self.y)]:
# past_angles[int(self.x)][int(self.y)].append(np.nanargmax(self.laser_range))
# lr2i = np.nanargmax(self.laser_range)
# else:
# lr2i = 0
# angle = 0
# for i in range(0,360):
# if np.isnan(self.laser_range[i]):
# angle = i
# lr2i = angle
if self.why_stop == 1:
lr2i = -25
self.why_stop = 0
if self.why_stop == 2:
lr2i = 35
self.why_stop = 0
# for i in range(0, 360):
# if (self.laser_range[i] not in nan_array):
# if (math.isnan(self.laser_range[i])):
# nan_array.append(i)
# lr2i = i
# size = len(self.occdata)
# size1 = len(self.occdata[0])
# middle = (int(size/2), int(size1/2))
# ref = (0, int(size1/2))
# lr2i = random.randint(0,360)
# for i in range(0,size):
# for j in range(0,size1):
# if ((self.occdata[i][j]) == 0):
# print(i,j)
# point = (i, j)
# hyp = int(math.dist(middle, point))
# adj = int(math.dist(middle, ref))
# angle = int(math.acos(adj/hyp))
# lr2i = angle
# lr2i = r_num
# self.get_logger().info('Picked direction: %d' % lr2i)
else:
lr2i = 0
self.get_logger().info('No data!')
# rotate to that direction
self.rotatebot(float(lr2i))
# start moving
self.get_logger().info('Start moving')
twist = Twist()
twist.linear.x = speedchange
twist.angular.z = 0.0
# not sure if this is really necessary, but things seem to work more
# reliably with this
time.sleep(1)
self.publisher_.publish(twist)
def stopbot(self):
self.get_logger().info('In stopbot')
# publish to cmd_vel to move TurtleBot
twist = Twist()
twist.linear.x = 0.0
twist.angular.z = 0.0
# time.sleep(1)
self.publisher_.publish(twist)
def mover(self):
try:
# initialize variable to write elapsed time to file
# contourCheck = 1
# find direction with the largest distance from the Lidar,
# rotate to that direction, and start moving
self.pick_direction()
while rclpy.ok():
if self.laser_range.size != 0:
# check distances in front of TurtleBot and find values less
# than stop_distance
# self.get_logger().info('Distances: %s' % str(self.laser_range[front_angles]))
lri = (self.laser_range[front_angles] < float(stop_distance)).nonzero()
if self.laser_range[270] > 0.8:
self.get_logger().info('Far from Wall')
self.why_stop = 1
self.stopbot()
self.pick_direction()
# if the list is not empty
if len(lri[0]) > 0:
self.why_stop = 2
self.get_logger().info('Going to crash')
# stop moving
self.stopbot()
# find direction with the largest distance from the Lidar
# rotate to that direction
# start moving
self.pick_direction()
self.turn_already = 0
# allow the callback functions to run
rclpy.spin_once(self)
except Exception as e:
print(e)
# Ctrl-c detected
finally:
# stop moving
self.stopbot()
def closure(mapdata):
# This function checks if mapdata contains a closed contour. The function
# assumes that the raw map data from SLAM has been modified so that
# -1 (unmapped) is now 0, and 0 (unoccupied) is now 1, and the occupied
# values go from 1 to 101.
# According to: https://stackoverflow.com/questions/17479606/detect-closed-contours?rq=1
# closed contours have larger areas than arc length, while open contours have larger
# arc length than area. But in my experience, open contours can have areas larger than
# the arc length, but closed contours tend to have areas much larger than the arc length
# So, we will check for contour closure by checking if any of the contours
# have areas that are more than 10 times larger than the arc length
# This value may need to be adjusted with more testing.
ALTHRESH = 10
# We will slightly fill in the contours to make them easier to detect
DILATE_PIXELS = 3
# assumes mapdata is uint8 and consists of 0 (unmapped), 1 (unoccupied),
# and other positive values up to 101 (occupied)
# so we will apply a threshold of 2 to create a binary image with the
# occupied pixels set to 255 and everything else is set to 0
# we will use OpenCV's threshold function for this
ret, img2 = cv2.threshold(mapdata, 2, 255, 0)
# we will perform some erosion and dilation to fill out the contours a
# little bit
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (DILATE_PIXELS, DILATE_PIXELS))
# img3 = cv2.erode(img2,element)
img4 = cv2.dilate(img2, element)
# use OpenCV's findContours function to identify contours
# OpenCV version 3 changed the number of return arguments, so we
# need to check the version of OpenCV installed so we know which argument
# to grab
fc = cv2.findContours(img4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
(major, minor, _) = cv2.__version__.split(".")
if (major == '3'):
contours = fc[1]
else:
contours = fc[0]
# find number of contours returned
lc = len(contours)
# rospy.loginfo('# Contours: %s', str(lc))
# create array to compute ratio of area to arc length
cAL = np.zeros((lc, 2))
for i in range(lc):
cAL[i, 0] = cv2.contourArea(contours[i])
cAL[i, 1] = cv2.arcLength(contours[i], True)
# closed contours tend to have a much higher area to arc length ratio,
# so if there are no contours with high ratios, we can safely say
# there are no closed contours
cALratio = cAL[:, 0] / cAL[:, 1]
# rospy.loginfo('Closure: %s', str(cALratio))
if np.any(cALratio > ALTHRESH):
return True
else:
return False
def main(args=None):
rclpy.init(args=args)
auto_nav = AutoNav()
auto_nav.mover()
# create matplotlib figure
# plt.ion()
# plt.show()
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
auto_nav.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()