forked from Telos4/RoboRally
359 lines
11 KiB
Python
359 lines
11 KiB
Python
# startup:
|
|
# roscore -> start ros
|
|
# rosparam set cv_camera/device_id 0 -> set appropriate camera device
|
|
# rosrun cv_camera cv_camera_node -> start the camera
|
|
# roslaunch aruco_detect aruco_detect.launch camera:=cv_camera image:=image_raw dictionary:=16 transport:= fiducial_len:=0.1 # aruco marker detection
|
|
# python fiducial_to_2d_pos_angle.py -> compute position and angle of markers in 2d plane
|
|
|
|
import sys
|
|
import rospy
|
|
import pygame
|
|
import numpy as np
|
|
import socket
|
|
import scipy.integrate
|
|
import copy
|
|
|
|
import threading
|
|
from copy import deepcopy
|
|
|
|
import matplotlib.pyplot as plt
|
|
import matplotlib.animation as anim
|
|
import matplotlib.patches as patch
|
|
|
|
import time
|
|
|
|
from casadi_opt import OpenLoopSolver
|
|
|
|
from marker_pos_angle.msg import id_pos_angle
|
|
|
|
class Robot:
|
|
def __init__(self, id, ip=None):
|
|
self.pos = None
|
|
self.orient = None
|
|
|
|
self.id = id
|
|
|
|
self.pos = None
|
|
self.euler = None
|
|
|
|
self.ip = ip
|
|
|
|
class Obstacle:
|
|
def __init__(self, id, radius):
|
|
self.id = id
|
|
self.pos = None
|
|
self.radius = radius
|
|
|
|
def f_ode(t, x, u):
|
|
# dynamical model of the two-wheeled robot
|
|
# TODO: find exact values for these parameters
|
|
r = 0.03
|
|
R = 0.05
|
|
d = 0.02
|
|
|
|
theta = x[2]
|
|
|
|
omega_r = u[0]
|
|
omega_l = u[1]
|
|
|
|
dx = np.zeros(3)
|
|
|
|
dx[0] = (r/2.0 * np.cos(theta) - r*d/(2.0*R) * np.sin(theta)) * omega_r \
|
|
+ (r/2.0 * np.cos(theta) + r*d/(2.0 * R) * np.sin(theta)) * omega_l
|
|
dx[1] = (r/2.0 * np.sin(theta) + r*d/(2.0*R) * np.cos(theta)) * omega_r \
|
|
+ (r/2 * np.sin(theta) - r*d/(2.0*R) * np.cos(theta)) * omega_l
|
|
dx[2] = -r/(2.0*R) * (omega_r - omega_l)
|
|
|
|
return dx
|
|
|
|
class RemoteController:
|
|
def __init__(self):
|
|
|
|
self.robots = [Robot(3, '192.168.1.103')]
|
|
|
|
self.robot_ids = {}
|
|
for r in self.robots:
|
|
self.robot_ids[r.id] = r
|
|
|
|
obst = [Obstacle(6, 0.175), Obstacle(5, 0.175), Obstacle(8, 0.175)]
|
|
|
|
self.obstacles = {}
|
|
for r in obst:
|
|
self.obstacles[r.id] = r
|
|
|
|
# connect to robot
|
|
self.rc_socket = socket.socket()
|
|
#self.rc_socket = None
|
|
try:
|
|
for r in self.robots:
|
|
self.rc_socket.connect((r.ip, 1234)) # connect to robot
|
|
except socket.error:
|
|
print("could not connect to socket")
|
|
self.rc_socket = None
|
|
|
|
|
|
self.t = time.time()
|
|
|
|
# variables for simulated state
|
|
self.x0 = None
|
|
self.ts = np.array([])
|
|
self.xs = []
|
|
|
|
# variables for measurements
|
|
self.tms_0 = None
|
|
self.xm_0 = None
|
|
self.tms = None
|
|
self.xms = None
|
|
|
|
# variable for mpc open loop
|
|
self.ol_x = None
|
|
self.ol_y = None
|
|
|
|
self.mutex = threading.Lock()
|
|
|
|
# ROS subscriber for detected markers
|
|
marker_sub = rospy.Subscriber("/marker_id_pos_angle", id_pos_angle, self.measurement_callback)
|
|
|
|
# pid parameters
|
|
self.controlling = False
|
|
|
|
# currently active control
|
|
self.u1 = 0.0
|
|
self.u2 = 0.0
|
|
|
|
# animation
|
|
self.fig = plt.figure()
|
|
self.ax = self.fig.add_subplot(1,1,1)
|
|
self.xdata, self.ydata = [], []
|
|
self.line, = self.ax.plot([],[], color='grey', linestyle=':')
|
|
self.line_sim, = self.ax.plot([], [])
|
|
self.line_ol, = self.ax.plot([],[], color='green', linestyle='--')
|
|
self.dirm, = self.ax.plot([], [])
|
|
self.dirs, = self.ax.plot([], [])
|
|
|
|
self.circles = []
|
|
for o in self.obstacles:
|
|
self.circles.append(patch.Circle((0.0, 0.0), radius=0.1, fill=False, color='red', linestyle='--'))
|
|
|
|
for s in self.circles:
|
|
self.ax.add_artist(s)
|
|
|
|
plt.xlabel('x-position')
|
|
plt.ylabel('y-position')
|
|
plt.grid()
|
|
|
|
self.ols = OpenLoopSolver()
|
|
self.ols.setup()
|
|
self.dt = self.ols.T / self.ols.N
|
|
|
|
self.target = (0.0, 0.0, 0.0)
|
|
|
|
# integrator
|
|
self.r = scipy.integrate.ode(f_ode)
|
|
self.omega_max = 5.0
|
|
|
|
|
|
def ani(self):
|
|
self.ani = anim.FuncAnimation(self.fig, init_func=self.ani_init, func=self.ani_update, interval=10, blit=True)
|
|
plt.ion()
|
|
plt.show(block=True)
|
|
|
|
def ani_init(self):
|
|
self.ax.set_xlim(-2, 2)
|
|
self.ax.set_ylim(-2, 2)
|
|
self.ax.set_aspect('equal', adjustable='box')
|
|
|
|
return self.line, self.line_sim, self.dirm, self.dirs, self.line_ol, self.circles[0], self.circles[1],self.circles[2],
|
|
|
|
def ani_update(self, frame):
|
|
#print("plotting")
|
|
self.mutex.acquire()
|
|
try:
|
|
# copy data for plot from global arrays
|
|
if self.tms is not None:
|
|
tm_local = deepcopy(self.tms)
|
|
xm_local = deepcopy(self.xms)
|
|
|
|
if len(tm_local) > 0:
|
|
# plot path of the robot
|
|
self.line.set_data(xm_local[:,0], xm_local[:,1])
|
|
|
|
# compute and plot direction the robot is facing
|
|
a = xm_local[-1, 0]
|
|
b = xm_local[-1, 1]
|
|
|
|
a2 = a + np.cos(xm_local[-1, 2]) * 0.2
|
|
b2 = b + np.sin(xm_local[-1, 2]) * 0.2
|
|
|
|
self.dirm.set_data(np.array([a, a2]), np.array([b, b2]))
|
|
|
|
ts_local = deepcopy(self.ts)
|
|
xs_local = deepcopy(self.xs)
|
|
|
|
if len(ts_local) > 0:
|
|
# plot simulated path of the robot
|
|
self.line_sim.set_data(xs_local[:,0], xs_local[:,1])
|
|
|
|
# compute and plot direction the robot is facing
|
|
a = xs_local[-1, 0]
|
|
b = xs_local[-1, 1]
|
|
|
|
a2 = a + np.cos(xs_local[-1, 2]) * 0.2
|
|
b2 = b + np.sin(xs_local[-1, 2]) * 0.2
|
|
|
|
self.dirs.set_data(np.array([a, a2]), np.array([b, b2]))
|
|
|
|
ol_x_local = deepcopy(self.ol_x)
|
|
ol_y_local = deepcopy(self.ol_y)
|
|
|
|
if ol_x_local is not None:
|
|
self.line_ol.set_data(ol_x_local, ol_y_local)
|
|
else:
|
|
self.line_ol.set_data([],[])
|
|
|
|
i = 0
|
|
obst_keys = self.obstacles.keys()
|
|
for s in self.circles:
|
|
o = self.obstacles[obst_keys[i]]
|
|
i = i + 1
|
|
|
|
if o.pos is not None:
|
|
s.center = o.pos
|
|
s.radius = o.radius
|
|
|
|
finally:
|
|
self.mutex.release()
|
|
|
|
return self.line, self.line_sim, self.dirm, self.dirs, self.line_ol, self.circles[0], self.circles[1],self.circles[2],
|
|
|
|
def measurement_callback(self, data):
|
|
# detect robots
|
|
if data.id in self.robot_ids:
|
|
r = self.robot_ids[data.id]
|
|
|
|
r.pos = (data.x, data.y) # only x and y component are important for us
|
|
r.euler = data.angle
|
|
|
|
# save measured position and angle for plotting
|
|
measurement = np.array([r.pos[0], r.pos[1], r.euler])
|
|
if self.tms_0 is None:
|
|
self.tms_0 = time.time()
|
|
self.xm_0 = measurement
|
|
|
|
self.mutex.acquire()
|
|
try:
|
|
self.tms = np.array([0.0])
|
|
self.xms = measurement
|
|
finally:
|
|
self.mutex.release()
|
|
else:
|
|
self.mutex.acquire()
|
|
try:
|
|
self.tms = np.vstack((self.tms, time.time() - self.tms_0))
|
|
self.xms = np.vstack((self.xms, measurement))
|
|
finally:
|
|
self.mutex.release()
|
|
|
|
# detect obstacles
|
|
if data.id in self.obstacles.keys():
|
|
obst = (data.x, data.y)
|
|
self.obstacles[data.id].pos = obst
|
|
|
|
def controller(self):
|
|
print("starting control")
|
|
while True:
|
|
|
|
# open loop controller
|
|
events = pygame.event.get()
|
|
for event in events:
|
|
if event.type == pygame.KEYDOWN:
|
|
if event.key == pygame.K_UP:
|
|
self.controlling = True
|
|
self.t = time.time()
|
|
elif event.key == pygame.K_DOWN:
|
|
self.controlling = False
|
|
if self.rc_socket:
|
|
self.rc_socket.send('(0.0,0.0)\n')
|
|
elif event.key == pygame.K_0:
|
|
self.target = (0.0, 0.0, 0.0)
|
|
elif event.key == pygame.K_1:
|
|
self.target = (0.5,0.5, -np.pi/2.0)
|
|
elif event.key == pygame.K_2:
|
|
self.target = (0.5, -0.5, 0.0)
|
|
elif event.key == pygame.K_3:
|
|
self.target = (-0.5,-0.5, np.pi/2.0)
|
|
elif event.key == pygame.K_4:
|
|
self.target = (-0.5,0.5, 0.0)
|
|
|
|
if self.controlling:
|
|
x_pred = self.get_measurement_prediction()
|
|
|
|
tmpc_start = time.time()
|
|
|
|
# solve mpc open loop problem
|
|
res = self.ols.solve(x_pred, self.target, self.obstacles)
|
|
|
|
us1 = res[0]
|
|
us2 = res[1]
|
|
|
|
# save open loop trajectories for plotting
|
|
self.mutex.acquire()
|
|
try:
|
|
self.ol_x = res[2]
|
|
self.ol_y = res[3]
|
|
finally:
|
|
self.mutex.release()
|
|
|
|
tmpc_end = time.time()
|
|
print("---------------- mpc solution took {} seconds".format(tmpc_end - tmpc_start))
|
|
dt_mpc = time.time() - self.t
|
|
if dt_mpc < self.dt: # wait until next control can be applied
|
|
print("sleeping for {} seconds...".format(self.dt - dt_mpc))
|
|
time.sleep(self.dt - dt_mpc)
|
|
|
|
# send controls to the robot
|
|
for i in range(0, 1): # option to use multistep mpc if len(range) > 1
|
|
u1 = us1[i]
|
|
u2 = us2[i]
|
|
if self.rc_socket:
|
|
self.rc_socket.send('({},{})\n'.format(u1, u2))
|
|
self.t = time.time() # save time the most recent control was applied
|
|
|
|
def get_measurement_prediction(self):
|
|
# get measurement
|
|
self.mutex.acquire()
|
|
try:
|
|
last_measurement = copy.deepcopy(self.xms[-1])
|
|
last_time = copy.deepcopy(self.tms[-1])
|
|
finally:
|
|
self.mutex.release()
|
|
|
|
# prediction of state at time the mpc will terminate
|
|
self.r.set_f_params(np.array([self.u1 * self.omega_max, self.u2 * self.omega_max]))
|
|
|
|
self.r.set_initial_value(last_measurement, last_time)
|
|
|
|
x_pred = self.r.integrate(self.r.t + self.dt)
|
|
|
|
return x_pred
|
|
|
|
|
|
def main(args):
|
|
rospy.init_node('controller_node', anonymous=True)
|
|
|
|
rc = RemoteController()
|
|
|
|
pygame.init()
|
|
|
|
screenheight = 480
|
|
screenwidth = 640
|
|
pygame.display.set_mode([screenwidth, screenheight])
|
|
|
|
#threading.Thread(target=rc.input_handling).start()
|
|
threading.Thread(target=rc.controller).start()
|
|
|
|
rc.ani()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main(sys.argv) |