-
Notifications
You must be signed in to change notification settings - Fork 0
/
rp_main.py
398 lines (326 loc) · 10.9 KB
/
rp_main.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
import argparse
import math
import os
import socket
import threading
import time
import traceback
from math import atan2, degrees, hypot, cos, sin
import RPi.GPIO as GPIO
# start pigpiod service
# os.system('sudo pigpiod')
import pigpio
from misc.connection_helper import ConnectionHelper
from misc.motor_controller import QuadMotorController
from misc.range_sensor import UltraSonicSensors
# init controllers
motor_controller = QuadMotorController()
# fuzzy_system = FuzzySystem()
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
pi = pigpio.pi()
r_range_sensors_pins = {
# R
(23, 24),
(23, 22),
(23, 27),
}
f_range_sensors_pins = {
# F
(23, 17),
(23, 4),
}
l_range_sensors_pins = {
# L
(23, 18),
(23, 25),
(23, 12),
}
method = "moo"
run = 'Running'
STOP = 'Stopped'
MANUAL = 'Manual'
status = run
# Simulation Timer
sim_time = 60.0
goal_threshold = 0.5
# x , y , theta
# robot position and orientation
x, y, theta = 0, 0, 0
# target position and orientation
x_d, y_d, theta_d = 0, 0, 0
dist = 9999
# range sensor value
dl = 2.2
df = 2.2
dr = 2.2
angle = 0
u, w = 10, 0
# angle between the robot heading and the vector connecting the robot center with the target,
# alpha in [-pi, +pi]
alpha = atan2(y_d - y, x_d - x) - theta
p = 0
ed = p
motor_status = STOP
first_time = True
# calculations precision
degree = 2
def range_updater():
global dl, df, dr, status
print('range Sensor thread is running')
# init range sensors
l_range_sensors = UltraSonicSensors(pi, l_range_sensors_pins)
f_range_sensors = UltraSonicSensors(pi, f_range_sensors_pins)
r_range_sensors = UltraSonicSensors(pi, r_range_sensors_pins)
while status == run:
try:
dl = l_range_sensors.update()
dl = round(dl / 50, 2)
df = f_range_sensors.update()
df = round(df / 50, 2)
dr = r_range_sensors.update()
dr = round(dr / 50, 2)
time.sleep(0.2)
except Exception as e:
print(e)
print(traceback.format_exc())
l_range_sensors.cancel()
f_range_sensors.cancel()
r_range_sensors.cancel()
pi.stop()
status = STOP
break
print('range Sensor thread is stopped')
def reverse(m_speed=None):
global motor_controller, motor_status
try:
motor_controller.move_backward(back_speed=m_speed)
# setLEDs(1, 0, 0, 1)
# print('straight')
except Exception as e:
motor_controller = QuadMotorController()
print(e)
print(traceback.format_exc())
def forwards(m_speed=None):
global motor_controller, motor_status
try:
print('forward')
motor_controller.move_forward(forward_speed=m_speed)
except Exception as e:
motor_controller = QuadMotorController()
print(e)
print(traceback.format_exc())
def turnright(m_speed=None):
global motor_controller, motor_status
try:
print('right')
motor_controller.move_right(right_speed=m_speed)
except Exception as e:
motor_controller = QuadMotorController()
print(e)
print(traceback.format_exc())
def turnleft(m_speed=None):
global motor_controller, motor_status
try:
print('left')
motor_controller.move_left(left_speed=m_speed)
except Exception as e:
motor_controller = QuadMotorController()
print(e)
print(traceback.format_exc())
def stopall(force=False):
global motor_controller, motor_status
try:
if force:
motor_controller.stopall()
else:
motor_controller.move_left(left_speed=0)
motor_status = 'stop'
except Exception as e:
motor_controller = QuadMotorController()
print(e)
print(traceback.format_exc())
# Helper Functions
def map(value, istart, istop, ostart, ostop):
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))
def pol2cart(rho, phi):
x = rho * cos(phi)
y = rho * sin(phi)
return x, y
def success():
global dist, goal_threshold
dist = hypot(x_d - x, y_d - y)
return dist < goal_threshold
def update_data():
global socket, dl, df, dr, alpha, p, ed, u, w, angle, first_time, method
if first_time:
message = {
"method": method
}
ConnectionHelper.send_json(socket, message)
ConnectionHelper.receive_json(socket)
first_time = False
# angle between the robot heading and the vector connecting the robot center with the target,
# alpha in [-pi, +pi]
alpha = atan2(y_d - y, x_d - x) - theta
alpha = ((-alpha + math.pi) % (2.0 * math.pi) - math.pi) * -1.0
# Distance from the center of the robot to the target
p_current = hypot(x_d - x, y_d - y)
ed = p_current - p
p = p_current
# take sensors current value
current_dl = dl
current_df = df
current_dr = dr
# current_dl = 4
# current_df = 4
# current_dr = 4
alpha = round(alpha, degree)
p = round(p, degree)
ed = round(ed, degree)
current_dl = round(current_dl, degree)
current_df = round(current_df, degree)
current_dr = round(current_dr, degree)
# ensure that data in fuzzy range
alpha = max(min(alpha, 4), -4)
p = max(min(p, 20), 0)
ed = max(min(ed, 1), -1)
current_dl = max(min(current_dl, 4), 0)
current_df = max(min(current_df, 4), 0)
current_dr = max(min(current_dr, 4), 0)
print(f"dl : {current_dl} df : {current_df} dr : {current_dr} alpha : {alpha} p : {p} ed : {ed}")
message = {
"dl": current_dl,
"df": current_df,
"dr": current_dr,
"alpha": alpha,
"p": p,
"ed": ed,
# map it to [0, 100]
"velocity": u
}
ConnectionHelper.send_json(socket, message)
result = ConnectionHelper.receive_json(socket)
print("Got >>", result)
if "u" in result and "w" in result:
u = result["u"]
w = result["w"]
else:
u = result["velocity"]
angle = result["angle"]
fb_speed = 0
lr_speed = 0
def auto_movement():
global x, y, theta, x_d, y_d, theta_d, dl, df, dr, p, ed, alpha, status, u, w, fb_speed, lr_speed, angle
print('auto movement thread is running')
move_time = 0.2
goal_reached = success()
while status == run and not goal_reached:
try:
# communicate with server
update_data()
if w is not None and w != 0:
degree_per_second = 375
w = w * move_time
# lr_speed = int(map(w, -5, 5, -100, 100))
lr_speed = round(abs(degrees(w) / degree_per_second), 2)
print('LR {} '.format(lr_speed))
if w > 0:
turnleft(100)
elif w < 0:
turnright(100)
time.sleep(lr_speed)
stopall()
# angular velocity
# a_degree = lr_speed * move_time / 360
theta += w
time.sleep(0.2)
if u is not None and u != 0:
forwards(100)
time.sleep(move_time * u)
stopall()
meter_per_second = 1.1
x_new, y_new = pol2cart(u * move_time * meter_per_second, theta)
x += x_new
y += y_new
# print_status(position, fb_speed, lr_speed, dl, df, dr)
goal_reached = success()
except Exception as e:
print(e)
print(traceback.format_exc())
break
print('Robot Stopped because ' + ('goal reached ' if goal_reached else 'Unknown Reason'))
time.sleep(0.5)
status = STOP
def print_status():
while status == run:
os.system('clear')
print('******************************')
print('lr speed is : {}\nfb speed is : {} '.format(fb_speed, lr_speed))
print('******************************')
print('alpha is : {} \ned is : {}\np is : {} '.format(alpha, ed, p))
print('******************************')
print('current Position is :{},{},{}'.format(x, y, degrees(theta)))
print('******************************')
print('Destination Position is :{},{},{}'.format(x_d, y_d, theta_d))
print('******************************')
print('Distance L:{} F:{} R:{}'.format(dl, df, dr))
print('******************************')
print('dist is :{}'.format(dist))
if dist < goal_threshold:
print('***********************GOAL***REACHED***************************************')
print('***********************GOAL***REACHED***************************************')
print('***********************GOAL***REACHED***************************************')
print('***********************GOAL***REACHED***************************************')
print('***********************GOAL***REACHED***************************************')
time.sleep(0.3)
def simulation_timer():
global status, sim_time
print('simulation timer has started')
if sim_time != -1:
end = time.time() + sim_time
while time.time() < end and status == run:
time.sleep(1)
status = STOP
time.sleep(2)
print('simulation timer has stopped')
if __name__ == '__main__':
try:
parser = argparse.ArgumentParser()
parser.add_argument('--host', type=str)
parser.add_argument('--port', type=int, default=8888)
parser.add_argument('--xd', type=int, default=0)
parser.add_argument('--yd', type=int, default=0)
arguments = parser.parse_args()
x_d = arguments.xd
y_d = arguments.yd
try:
socket.connect((arguments.host, arguments.port))
print('connected to server ' + arguments.host + ':' + str(arguments.port))
except Exception as e:
print(e)
print(traceback.format_exc())
status = STOP
range_sensor_thread = threading.Thread(target=range_updater)
# fuzzy_thread = threading.Thread(target=do_fuzzy)
auto_movement_thread = threading.Thread(target=auto_movement)
simulation_timer_thread = threading.Thread(target=simulation_timer)
print_thread = threading.Thread(target=print_status)
# movement_thread = threading.Thread(target=movement)
range_sensor_thread.start()
time.sleep(1)
# movement_thread.start()
# fuzzy_thread.start()
print_thread.start()
simulation_timer_thread.start()
auto_movement_thread.start()
# Join Threads to Stop together
# movement_thread.join()
range_sensor_thread.join()
# fuzzy_thread.join()
auto_movement_thread.join()
simulation_timer_thread.join()
print_thread.join()
finally:
# Force STOP MOTORS
stopall(force=True)
GPIO.cleanup()