first commit
This commit is contained in:
27
CMakeLists.txt
Normal file
27
CMakeLists.txt
Normal file
@@ -0,0 +1,27 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(virtual_joystick_teleop)
|
||||
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
geometry_msgs
|
||||
rospy
|
||||
)
|
||||
|
||||
catkin_python_setup()
|
||||
|
||||
catkin_package(
|
||||
CATKIN_DEPENDS geometry_msgs rospy
|
||||
)
|
||||
|
||||
catkin_install_python(
|
||||
PROGRAMS scripts/virtual_joystick_node.py
|
||||
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(
|
||||
DIRECTORY launch
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
|
||||
)
|
||||
|
||||
if(CATKIN_ENABLE_TESTING)
|
||||
catkin_add_nosetests(test/test_teleop_model.py)
|
||||
endif()
|
||||
76
README.md
Normal file
76
README.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# virtual_joystick_teleop
|
||||
|
||||
A ROS Noetic Python 3 GUI for driving a differential-drive robot from the
|
||||
keyboard or mouse. The virtual joystick shows the active arrow-key direction
|
||||
and can also be dragged for proportional control. The signed velocity controls
|
||||
follow the layout and interaction pattern of `rqt_robot_steering`, and the node publishes
|
||||
`geometry_msgs/Twist` on `/cmd_vel` by default.
|
||||
|
||||
## Controls
|
||||
|
||||
| Input | Command |
|
||||
| --- | --- |
|
||||
| Up / Down | Positive / negative `linear.x` |
|
||||
| Left / Right | Positive / negative `angular.z` |
|
||||
| Drag joystick | Proportional linear and angular command |
|
||||
| Keyboard/joystick linear slider | Set the speed used by Up / Down |
|
||||
| Keyboard/joystick yaw slider | Set the speed used by Left / Right |
|
||||
| Vertical linear slider | Set signed `linear.x` directly |
|
||||
| Horizontal yaw slider | Set signed `angular.z` directly |
|
||||
| `+`, `0`, `-` / arrows | Step, zero, or reverse one velocity axis |
|
||||
| Min/max spin boxes | Change signed runtime limits, like rqt steering |
|
||||
| STOP, Space, or Esc | Immediately publish a zero command |
|
||||
| Restore defaults | Restore the startup speed values |
|
||||
|
||||
Multiple arrow keys can be held together. For example, Up + Left commands
|
||||
forward motion while turning left. Dragging the joystick provides proportional
|
||||
control up to the configured speed. Keyboard and joystick inputs stop when they
|
||||
are released. Like `rqt_robot_steering`, the signed velocity sliders keep their
|
||||
command until an axis is reset to `0` or STOP is pressed. Moving focus away from
|
||||
the GUI, closing the window, or shutting down ROS still publishes a zero command.
|
||||
While a min/max field has focus, arrow keys only edit its number and do not
|
||||
control the robot. Press Enter or click outside the field to apply the value;
|
||||
focus then returns to the teleoperation window.
|
||||
|
||||
## Build and run
|
||||
|
||||
```bash
|
||||
cd /home/duongtd/T800_ws
|
||||
catkin_make --pkg virtual_joystick_teleop
|
||||
source devel/setup.bash
|
||||
roslaunch virtual_joystick_teleop virtual_joystick_teleop.launch
|
||||
```
|
||||
|
||||
Keep the GUI window focused while using the arrow keys. To inspect the output:
|
||||
|
||||
```bash
|
||||
rostopic echo /cmd_vel
|
||||
```
|
||||
|
||||
To remap the output topic or publish rate:
|
||||
|
||||
```bash
|
||||
roslaunch virtual_joystick_teleop virtual_joystick_teleop.launch \
|
||||
cmd_vel_topic:=/robot/cmd_vel publish_rate:=30.0
|
||||
```
|
||||
|
||||
The initial speeds, adjustment steps, signed min/max limits, and UI limit
|
||||
ceilings are private ROS parameters in `launch/virtual_joystick_teleop.launch`.
|
||||
Linear values use m/s and yaw values use rad/s. The default linear range is
|
||||
`[-2.0, 2.0]` m/s. The spin boxes can expand it up to
|
||||
`linear_limit_ceiling`, which defaults to 5.0 m/s in either direction.
|
||||
|
||||
For example, to allow the maximum-limit slider to reach 8.0 m/s while starting
|
||||
with a 3.0 m/s limit:
|
||||
|
||||
```bash
|
||||
roslaunch virtual_joystick_teleop virtual_joystick_teleop.launch \
|
||||
min_linear_command:=-3.0 max_linear_speed:=3.0 linear_limit_ceiling:=8.0
|
||||
```
|
||||
|
||||
## Safety note
|
||||
|
||||
Do not let this node and a navigation controller command the same robot topic
|
||||
at the same time. Use a velocity multiplexer when several command sources must
|
||||
share control, and test with the drive wheels raised or the motor driver
|
||||
disabled before enabling motion on hardware.
|
||||
34
launch/virtual_joystick_teleop.launch
Normal file
34
launch/virtual_joystick_teleop.launch
Normal file
@@ -0,0 +1,34 @@
|
||||
<launch>
|
||||
<arg name="cmd_vel_topic" default="/cmd_vel"/>
|
||||
<arg name="publish_rate" default="20.0"/>
|
||||
<arg name="max_linear_speed" default="2.00"/>
|
||||
<arg name="max_angular_speed" default="2.00"/>
|
||||
<arg name="min_linear_command" default="-2.00"/>
|
||||
<arg name="min_angular_command" default="-2.00"/>
|
||||
<arg name="linear_limit_ceiling" default="5.00"/>
|
||||
<arg name="angular_limit_ceiling" default="8.00"/>
|
||||
|
||||
<node pkg="virtual_joystick_teleop"
|
||||
type="virtual_joystick_node.py"
|
||||
name="virtual_joystick_teleop"
|
||||
output="screen">
|
||||
<param name="cmd_vel_topic" value="$(arg cmd_vel_topic)"/>
|
||||
<param name="publish_rate" value="$(arg publish_rate)"/>
|
||||
|
||||
<param name="linear_speed" value="0.30"/>
|
||||
<param name="angular_speed" value="0.70"/>
|
||||
<param name="linear_step" value="0.05"/>
|
||||
<param name="angular_step" value="0.10"/>
|
||||
|
||||
<param name="min_linear_speed" value="0.05"/>
|
||||
<param name="max_linear_speed" value="$(arg max_linear_speed)"/>
|
||||
<param name="min_angular_speed" value="0.10"/>
|
||||
<param name="max_angular_speed" value="$(arg max_angular_speed)"/>
|
||||
<param name="min_linear_command" value="$(arg min_linear_command)"/>
|
||||
<param name="min_angular_command" value="$(arg min_angular_command)"/>
|
||||
|
||||
<!-- UI ceilings for the adjustable maximum-speed sliders. -->
|
||||
<param name="linear_limit_ceiling" value="$(arg linear_limit_ceiling)"/>
|
||||
<param name="angular_limit_ceiling" value="$(arg angular_limit_ceiling)"/>
|
||||
</node>
|
||||
</launch>
|
||||
21
package.xml
Normal file
21
package.xml
Normal file
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>virtual_joystick_teleop</name>
|
||||
<version>0.1.0</version>
|
||||
<description>Keyboard teleoperation GUI with a virtual joystick for ROS Noetic.</description>
|
||||
|
||||
<maintainer email="duongtd@example.com">duongtd</maintainer>
|
||||
<license>BSD-3-Clause</license>
|
||||
|
||||
<buildtool_depend>catkin</buildtool_depend>
|
||||
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>rospy</depend>
|
||||
<exec_depend>python3-tk</exec_depend>
|
||||
|
||||
<test_depend>python3-nose</test_depend>
|
||||
|
||||
<export>
|
||||
<architecture_independent/>
|
||||
</export>
|
||||
</package>
|
||||
BIN
scripts/__pycache__/virtual_joystick_node.cpython-38.pyc
Normal file
BIN
scripts/__pycache__/virtual_joystick_node.cpython-38.pyc
Normal file
Binary file not shown.
877
scripts/virtual_joystick_node.py
Executable file
877
scripts/virtual_joystick_node.py
Executable file
@@ -0,0 +1,877 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tkinter keyboard teleoperation GUI for ROS Noetic."""
|
||||
|
||||
import math
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
|
||||
import rospy
|
||||
from geometry_msgs.msg import Twist
|
||||
|
||||
from virtual_joystick_teleop import TeleopModel
|
||||
|
||||
|
||||
class VirtualJoystickApp:
|
||||
"""Owns the Tk GUI and publishes its teleoperation state as Twist."""
|
||||
|
||||
CANVAS_SIZE = 280
|
||||
JOYSTICK_CENTER = CANVAS_SIZE // 2
|
||||
JOYSTICK_RADIUS = 98
|
||||
KNOB_RADIUS = 20
|
||||
KNOB_TRAVEL = 62
|
||||
KEY_RELEASE_DEBOUNCE_MS = 25
|
||||
|
||||
def __init__(self):
|
||||
self._closed = False
|
||||
self._release_jobs = {}
|
||||
|
||||
self._publish_rate = self._positive_param("~publish_rate", 20.0)
|
||||
self._publish_period_ms = max(1, int(round(1000.0 / self._publish_rate)))
|
||||
self._cmd_vel_topic = str(rospy.get_param("~cmd_vel_topic", "/cmd_vel"))
|
||||
if not self._cmd_vel_topic:
|
||||
raise ValueError("~cmd_vel_topic must not be empty")
|
||||
|
||||
self.model = TeleopModel(
|
||||
linear_speed=rospy.get_param("~linear_speed", 0.30),
|
||||
angular_speed=rospy.get_param("~angular_speed", 0.70),
|
||||
linear_step=rospy.get_param("~linear_step", 0.05),
|
||||
angular_step=rospy.get_param("~angular_step", 0.10),
|
||||
min_linear_speed=rospy.get_param("~min_linear_speed", 0.05),
|
||||
max_linear_speed=rospy.get_param("~max_linear_speed", 2.00),
|
||||
min_angular_speed=rospy.get_param("~min_angular_speed", 0.10),
|
||||
max_angular_speed=rospy.get_param("~max_angular_speed", 2.00),
|
||||
min_linear_command=rospy.get_param("~min_linear_command", -2.00),
|
||||
min_angular_command=rospy.get_param("~min_angular_command", -2.00),
|
||||
)
|
||||
self._default_linear_speed = self.model.linear_speed
|
||||
self._default_angular_speed = self.model.angular_speed
|
||||
self._default_max_linear_speed = self.model.max_linear_speed
|
||||
self._default_max_angular_speed = self.model.max_angular_speed
|
||||
self._default_min_linear_command = self.model.min_linear_command
|
||||
self._default_min_angular_command = self.model.min_angular_command
|
||||
self._linear_limit_ceiling = max(
|
||||
self.model.max_linear_speed,
|
||||
self._positive_param("~linear_limit_ceiling", 5.00),
|
||||
)
|
||||
self._angular_limit_ceiling = max(
|
||||
self.model.max_angular_speed,
|
||||
self._positive_param("~angular_limit_ceiling", 8.00),
|
||||
)
|
||||
self._updating_velocity_controls = False
|
||||
self._limit_editors = {}
|
||||
|
||||
self.publisher = rospy.Publisher(self._cmd_vel_topic, Twist, queue_size=1)
|
||||
rospy.on_shutdown(self._publish_stop)
|
||||
|
||||
self.root = tk.Tk()
|
||||
self.root.title("ROS Virtual Joystick - Điều khiển robot")
|
||||
self.root.resizable(False, False)
|
||||
self.root.protocol("WM_DELETE_WINDOW", self._request_shutdown)
|
||||
self.root.bind_all("<KeyPress>", self._on_key_press, add="+")
|
||||
self.root.bind_all("<KeyRelease>", self._on_key_release, add="+")
|
||||
self.root.bind_all("<ButtonPress-1>", self._on_mouse_press, add="+")
|
||||
self.root.bind("<FocusOut>", self._on_focus_out, add="+")
|
||||
|
||||
self._configure_style()
|
||||
self._build_gui()
|
||||
self._refresh_view()
|
||||
self._lock_window_size()
|
||||
self.root.after(self._publish_period_ms, self._publish_tick)
|
||||
self.root.after(100, self._focus_window)
|
||||
|
||||
rospy.loginfo(
|
||||
"Virtual joystick publishing to %s at %.1f Hz",
|
||||
self._cmd_vel_topic,
|
||||
self._publish_rate,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _positive_param(name, default):
|
||||
value = rospy.get_param(name, default)
|
||||
try:
|
||||
value = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("{} must be a positive finite number".format(name)) from exc
|
||||
if not math.isfinite(value) or value <= 0.0:
|
||||
raise ValueError("{} must be a positive finite number".format(name))
|
||||
return value
|
||||
|
||||
def _configure_style(self):
|
||||
style = ttk.Style(self.root)
|
||||
if "clam" in style.theme_names():
|
||||
style.theme_use("clam")
|
||||
style.configure("Title.TLabel", font=("Sans", 18, "bold"))
|
||||
style.configure("Hint.TLabel", font=("Sans", 10))
|
||||
style.configure(
|
||||
"Speed.TLabel", font=("Sans", 14, "bold"), anchor="center"
|
||||
)
|
||||
style.configure("Command.TLabel", font=("Monospace", 11, "bold"))
|
||||
style.configure("Stop.TButton", font=("Sans", 11, "bold"), padding=8)
|
||||
|
||||
def _lock_window_size(self):
|
||||
"""Freeze the initial geometry so changing numeric labels cannot resize it."""
|
||||
self.root.update_idletasks()
|
||||
width = self.root.winfo_reqwidth()
|
||||
height = self.root.winfo_reqheight()
|
||||
self.root.geometry("{}x{}".format(width, height))
|
||||
self.root.minsize(width, height)
|
||||
self.root.maxsize(width, height)
|
||||
|
||||
def _build_gui(self):
|
||||
container = ttk.Frame(self.root, padding=16)
|
||||
container.grid(row=0, column=0, sticky="nsew")
|
||||
|
||||
ttk.Label(container, text="ROS Virtual Joystick", style="Title.TLabel").grid(
|
||||
row=0, column=0, columnspan=2, pady=(0, 4)
|
||||
)
|
||||
ttk.Label(
|
||||
container,
|
||||
text="Giữ phím mũi tên hoặc kéo joystick. Nhả ra để dừng.",
|
||||
style="Hint.TLabel",
|
||||
).grid(row=1, column=0, columnspan=2, pady=(0, 12))
|
||||
|
||||
self.canvas = tk.Canvas(
|
||||
container,
|
||||
width=self.CANVAS_SIZE,
|
||||
height=self.CANVAS_SIZE,
|
||||
bg="#111827",
|
||||
highlightthickness=0,
|
||||
)
|
||||
self.canvas.grid(row=2, column=0, padx=(0, 18))
|
||||
self._draw_joystick()
|
||||
self.canvas.bind("<ButtonPress-1>", self._on_joystick_drag)
|
||||
self.canvas.bind("<B1-Motion>", self._on_joystick_drag)
|
||||
self.canvas.bind("<ButtonRelease-1>", self._on_joystick_release)
|
||||
|
||||
controls = ttk.Frame(container)
|
||||
controls.grid(row=2, column=1, sticky="nsew")
|
||||
|
||||
self.linear_speed_var = tk.StringVar()
|
||||
self.angular_speed_var = tk.StringVar()
|
||||
self.keyboard_linear_speed_var = tk.StringVar()
|
||||
self.keyboard_angular_speed_var = tk.StringVar()
|
||||
self.max_linear_speed_var = tk.StringVar()
|
||||
self.min_linear_command_var = tk.StringVar()
|
||||
self.max_angular_speed_var = tk.StringVar()
|
||||
self.min_angular_command_var = tk.StringVar()
|
||||
self.command_var = tk.StringVar()
|
||||
self.status_var = tk.StringVar(value="Sẵn sàng - cửa sổ đang nhận điều khiển")
|
||||
self._speed_controls = {}
|
||||
|
||||
topic_bar = ttk.Frame(controls)
|
||||
topic_bar.grid(row=0, column=0, sticky="ew", pady=(0, 8))
|
||||
ttk.Label(topic_bar, text="Topic:").grid(row=0, column=0, padx=(0, 6))
|
||||
ttk.Label(topic_bar, text=self._cmd_vel_topic, style="Command.TLabel").grid(
|
||||
row=0, column=1, sticky="w"
|
||||
)
|
||||
ttk.Button(
|
||||
topic_bar,
|
||||
text="STOP",
|
||||
command=self._emergency_stop,
|
||||
style="Stop.TButton",
|
||||
takefocus=False,
|
||||
).grid(row=0, column=2, padx=(10, 0))
|
||||
topic_bar.columnconfigure(1, weight=1)
|
||||
|
||||
self._add_keyboard_speed_controls(controls, row=1)
|
||||
self._add_linear_steering_control(controls, row=2)
|
||||
self._add_angular_steering_control(controls, row=3)
|
||||
|
||||
ttk.Label(
|
||||
controls,
|
||||
text="Slider giữ lệnh; nhấn 0 hoặc STOP để dừng.",
|
||||
style="Hint.TLabel",
|
||||
width=46,
|
||||
anchor="center",
|
||||
).grid(row=4, column=0, sticky="ew", pady=(0, 8))
|
||||
|
||||
ttk.Label(controls, text="Lệnh đang publish").grid(
|
||||
row=5, column=0, sticky="w"
|
||||
)
|
||||
ttk.Label(
|
||||
controls,
|
||||
textvariable=self.command_var,
|
||||
style="Command.TLabel",
|
||||
width=24,
|
||||
anchor="w",
|
||||
).grid(row=6, column=0, sticky="w", pady=(4, 8))
|
||||
ttk.Button(
|
||||
controls,
|
||||
text="Khôi phục giới hạn mặc định",
|
||||
command=self._reset_speeds,
|
||||
takefocus=False,
|
||||
).grid(row=7, column=0, sticky="ew")
|
||||
|
||||
ttk.Label(
|
||||
container,
|
||||
textvariable=self.status_var,
|
||||
style="Hint.TLabel",
|
||||
width=74,
|
||||
anchor="center",
|
||||
).grid(row=3, column=0, columnspan=2, pady=(12, 0))
|
||||
|
||||
def _draw_joystick(self):
|
||||
center = self.JOYSTICK_CENTER
|
||||
radius = self.JOYSTICK_RADIUS
|
||||
self.canvas.create_oval(
|
||||
center - radius,
|
||||
center - radius,
|
||||
center + radius,
|
||||
center + radius,
|
||||
fill="#1f2937",
|
||||
outline="#64748b",
|
||||
width=3,
|
||||
)
|
||||
self.canvas.create_line(
|
||||
center - radius + 16,
|
||||
center,
|
||||
center + radius - 16,
|
||||
center,
|
||||
fill="#475569",
|
||||
width=2,
|
||||
)
|
||||
self.canvas.create_line(
|
||||
center,
|
||||
center - radius + 16,
|
||||
center,
|
||||
center + radius - 16,
|
||||
fill="#475569",
|
||||
width=2,
|
||||
)
|
||||
self.canvas.create_text(center, 22, text="TIẾN", fill="#cbd5e1")
|
||||
self.canvas.create_text(
|
||||
center, self.CANVAS_SIZE - 22, text="LÙI", fill="#cbd5e1"
|
||||
)
|
||||
self.canvas.create_text(25, center, text="TRÁI", fill="#cbd5e1")
|
||||
self.canvas.create_text(
|
||||
self.CANVAS_SIZE - 25, center, text="PHẢI", fill="#cbd5e1"
|
||||
)
|
||||
knob_radius = self.KNOB_RADIUS
|
||||
self.knob = self.canvas.create_oval(
|
||||
center - knob_radius,
|
||||
center - knob_radius,
|
||||
center + knob_radius,
|
||||
center + knob_radius,
|
||||
fill="#94a3b8",
|
||||
outline="#e2e8f0",
|
||||
width=2,
|
||||
)
|
||||
|
||||
def _add_keyboard_speed_controls(self, parent, row):
|
||||
panel = ttk.LabelFrame(
|
||||
parent, text="Tốc độ phím & joystick", padding=(10, 6)
|
||||
)
|
||||
panel.grid(row=row, column=0, sticky="ew", pady=(0, 8))
|
||||
|
||||
self._add_keyboard_speed_row(
|
||||
panel,
|
||||
row=0,
|
||||
speed_type="linear",
|
||||
title="↑ / ↓ Linear",
|
||||
value_var=self.keyboard_linear_speed_var,
|
||||
minimum=self.model.min_linear_speed,
|
||||
maximum=self.model.max_linear_speed,
|
||||
step=self.model.linear_step,
|
||||
)
|
||||
self._add_keyboard_speed_row(
|
||||
panel,
|
||||
row=1,
|
||||
speed_type="angular",
|
||||
title="← / → Yaw",
|
||||
value_var=self.keyboard_angular_speed_var,
|
||||
minimum=self.model.min_angular_speed,
|
||||
maximum=self.model.max_angular_speed,
|
||||
step=self.model.angular_step,
|
||||
)
|
||||
panel.columnconfigure(2, weight=1)
|
||||
|
||||
def _add_keyboard_speed_row(
|
||||
self, parent, row, speed_type, title, value_var, minimum, maximum, step
|
||||
):
|
||||
ttk.Label(parent, text=title, width=14).grid(
|
||||
row=row, column=0, sticky="w", pady=2
|
||||
)
|
||||
ttk.Button(
|
||||
parent,
|
||||
text="−",
|
||||
width=3,
|
||||
command=lambda axis=speed_type: self._adjust_keyboard_speed(axis, -1),
|
||||
takefocus=False,
|
||||
).grid(row=row, column=1, padx=(4, 4))
|
||||
|
||||
scale_var = tk.DoubleVar(value=minimum)
|
||||
scale = ttk.Scale(
|
||||
parent,
|
||||
from_=minimum,
|
||||
to=maximum,
|
||||
variable=scale_var,
|
||||
command=lambda value, axis=speed_type: self._on_keyboard_speed_slider(
|
||||
axis, value
|
||||
),
|
||||
)
|
||||
scale.grid(row=row, column=2, sticky="ew", pady=2)
|
||||
|
||||
ttk.Button(
|
||||
parent,
|
||||
text="+",
|
||||
width=3,
|
||||
command=lambda axis=speed_type: self._adjust_keyboard_speed(axis, 1),
|
||||
takefocus=False,
|
||||
).grid(row=row, column=3, padx=(4, 6))
|
||||
ttk.Label(parent, textvariable=value_var, width=12, anchor="e").grid(
|
||||
row=row, column=4, sticky="e"
|
||||
)
|
||||
|
||||
self._speed_controls["keyboard_{}".format(speed_type)] = {
|
||||
"scale": scale,
|
||||
"scale_var": scale_var,
|
||||
"step": step,
|
||||
}
|
||||
|
||||
def _add_linear_steering_control(self, parent, row):
|
||||
panel = ttk.LabelFrame(parent, text="Linear x (m/s)", padding=(10, 6))
|
||||
panel.grid(row=row, column=0, sticky="ew", pady=(0, 8))
|
||||
|
||||
button_column = ttk.Frame(panel)
|
||||
button_column.grid(row=0, column=0, rowspan=3, padx=(0, 8))
|
||||
ttk.Button(
|
||||
button_column,
|
||||
text="+",
|
||||
width=3,
|
||||
command=lambda: self._adjust_velocity_command("linear", 1),
|
||||
takefocus=False,
|
||||
).grid(row=0, column=0)
|
||||
ttk.Button(
|
||||
button_column,
|
||||
text="0",
|
||||
width=3,
|
||||
command=lambda: self._zero_velocity_axis("linear"),
|
||||
takefocus=False,
|
||||
).grid(row=1, column=0, pady=34)
|
||||
ttk.Button(
|
||||
button_column,
|
||||
text="−",
|
||||
width=3,
|
||||
command=lambda: self._adjust_velocity_command("linear", -1),
|
||||
takefocus=False,
|
||||
).grid(row=2, column=0)
|
||||
|
||||
scale_var = tk.DoubleVar(value=0.0)
|
||||
scale = tk.Scale(
|
||||
panel,
|
||||
from_=self.model.max_linear_speed,
|
||||
to=self.model.min_linear_command,
|
||||
resolution=self.model.linear_step,
|
||||
variable=scale_var,
|
||||
command=lambda value: self._on_velocity_slider("linear", value),
|
||||
orient=tk.VERTICAL,
|
||||
length=205,
|
||||
showvalue=False,
|
||||
sliderlength=18,
|
||||
width=14,
|
||||
troughcolor="#cbd5e1",
|
||||
highlightthickness=0,
|
||||
)
|
||||
scale.grid(row=0, column=1, rowspan=3)
|
||||
|
||||
max_spin = self._make_limit_spinbox(
|
||||
panel,
|
||||
variable=self.max_linear_speed_var,
|
||||
minimum=0.0,
|
||||
maximum=self._linear_limit_ceiling,
|
||||
increment=self.model.linear_step,
|
||||
callback=lambda: self._apply_limit_value("linear", "max"),
|
||||
)
|
||||
max_spin.grid(row=0, column=2, sticky="n", padx=(10, 0))
|
||||
ttk.Label(
|
||||
panel,
|
||||
textvariable=self.linear_speed_var,
|
||||
style="Speed.TLabel",
|
||||
width=15,
|
||||
anchor="center",
|
||||
).grid(row=1, column=2, padx=(10, 0))
|
||||
min_spin = self._make_limit_spinbox(
|
||||
panel,
|
||||
variable=self.min_linear_command_var,
|
||||
minimum=-self._linear_limit_ceiling,
|
||||
maximum=0.0,
|
||||
increment=self.model.linear_step,
|
||||
callback=lambda: self._apply_limit_value("linear", "min"),
|
||||
)
|
||||
min_spin.grid(row=2, column=2, sticky="s", padx=(10, 0))
|
||||
|
||||
self._speed_controls["linear"] = {
|
||||
"scale": scale,
|
||||
"scale_var": scale_var,
|
||||
}
|
||||
|
||||
def _add_angular_steering_control(self, parent, row):
|
||||
panel = ttk.LabelFrame(parent, text="Angular z / yaw (rad/s)", padding=(10, 6))
|
||||
panel.grid(row=row, column=0, sticky="ew", pady=(0, 8))
|
||||
|
||||
scale_var = tk.DoubleVar(value=0.0)
|
||||
scale = tk.Scale(
|
||||
panel,
|
||||
from_=self.model.max_angular_speed,
|
||||
to=self.model.min_angular_command,
|
||||
resolution=self.model.angular_step,
|
||||
variable=scale_var,
|
||||
command=lambda value: self._on_velocity_slider("angular", value),
|
||||
orient=tk.HORIZONTAL,
|
||||
length=260,
|
||||
showvalue=False,
|
||||
sliderlength=18,
|
||||
width=14,
|
||||
troughcolor="#cbd5e1",
|
||||
highlightthickness=0,
|
||||
)
|
||||
scale.grid(row=0, column=0, columnspan=3, sticky="ew")
|
||||
|
||||
ttk.Button(
|
||||
panel,
|
||||
text="←",
|
||||
width=4,
|
||||
command=lambda: self._adjust_velocity_command("angular", 1),
|
||||
takefocus=False,
|
||||
).grid(row=1, column=0, sticky="w")
|
||||
ttk.Button(
|
||||
panel,
|
||||
text="0",
|
||||
width=4,
|
||||
command=lambda: self._zero_velocity_axis("angular"),
|
||||
takefocus=False,
|
||||
).grid(row=1, column=1)
|
||||
ttk.Button(
|
||||
panel,
|
||||
text="→",
|
||||
width=4,
|
||||
command=lambda: self._adjust_velocity_command("angular", -1),
|
||||
takefocus=False,
|
||||
).grid(row=1, column=2, sticky="e")
|
||||
|
||||
max_spin = self._make_limit_spinbox(
|
||||
panel,
|
||||
variable=self.max_angular_speed_var,
|
||||
minimum=0.0,
|
||||
maximum=self._angular_limit_ceiling,
|
||||
increment=self.model.angular_step,
|
||||
callback=lambda: self._apply_limit_value("angular", "max"),
|
||||
)
|
||||
max_spin.grid(row=2, column=0, sticky="w", pady=(6, 0))
|
||||
ttk.Label(
|
||||
panel,
|
||||
textvariable=self.angular_speed_var,
|
||||
style="Speed.TLabel",
|
||||
width=15,
|
||||
anchor="center",
|
||||
).grid(row=2, column=1, pady=(6, 0))
|
||||
min_spin = self._make_limit_spinbox(
|
||||
panel,
|
||||
variable=self.min_angular_command_var,
|
||||
minimum=-self._angular_limit_ceiling,
|
||||
maximum=0.0,
|
||||
increment=self.model.angular_step,
|
||||
callback=lambda: self._apply_limit_value("angular", "min"),
|
||||
)
|
||||
min_spin.grid(row=2, column=2, sticky="e", pady=(6, 0))
|
||||
|
||||
panel.columnconfigure(1, weight=1)
|
||||
self._speed_controls["angular"] = {
|
||||
"scale": scale,
|
||||
"scale_var": scale_var,
|
||||
}
|
||||
|
||||
def _make_limit_spinbox(
|
||||
self, parent, variable, minimum, maximum, increment, callback
|
||||
):
|
||||
spinbox = ttk.Spinbox(
|
||||
parent,
|
||||
from_=minimum,
|
||||
to=maximum,
|
||||
increment=increment,
|
||||
textvariable=variable,
|
||||
width=8,
|
||||
)
|
||||
self._limit_editors[spinbox] = callback
|
||||
spinbox.bind(
|
||||
"<Return>",
|
||||
lambda _event: self._commit_limit_edit(callback),
|
||||
)
|
||||
spinbox.bind(
|
||||
"<KP_Enter>",
|
||||
lambda _event: self._commit_limit_edit(callback),
|
||||
)
|
||||
spinbox.bind("<FocusOut>", lambda _event: callback())
|
||||
return spinbox
|
||||
|
||||
def _commit_limit_edit(self, callback):
|
||||
"""Apply a Spinbox value and return arrow-key focus to teleoperation."""
|
||||
callback()
|
||||
self.root.after_idle(self._focus_window)
|
||||
return "break"
|
||||
|
||||
def _focus_window(self):
|
||||
if not self._closed:
|
||||
self.root.focus_set()
|
||||
|
||||
def _on_key_press(self, event):
|
||||
key = event.keysym
|
||||
if key in ("space", "Escape"):
|
||||
self._emergency_stop()
|
||||
return "break"
|
||||
if key not in TeleopModel.SUPPORTED_KEYS:
|
||||
return
|
||||
if self._is_limit_editor(event.widget):
|
||||
# Let the Spinbox handle arrows without forwarding them to teleop.
|
||||
return
|
||||
pending_release = self._release_jobs.pop(key, None)
|
||||
if pending_release is not None:
|
||||
self.root.after_cancel(pending_release)
|
||||
self.model.release_joystick()
|
||||
self.model.set_key(key, True)
|
||||
self.status_var.set("Phím đang giữ: {}".format(self._active_keys_text()))
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
return "break"
|
||||
|
||||
def _on_key_release(self, event):
|
||||
key = event.keysym
|
||||
if key not in TeleopModel.SUPPORTED_KEYS:
|
||||
return
|
||||
if self._is_limit_editor(event.widget):
|
||||
return
|
||||
pending_release = self._release_jobs.pop(key, None)
|
||||
if pending_release is not None:
|
||||
self.root.after_cancel(pending_release)
|
||||
self._release_jobs[key] = self.root.after(
|
||||
self.KEY_RELEASE_DEBOUNCE_MS,
|
||||
lambda released_key=key: self._finish_key_release(released_key),
|
||||
)
|
||||
return "break"
|
||||
|
||||
def _on_mouse_press(self, event):
|
||||
"""Commit an editor when the user clicks anywhere outside it."""
|
||||
focused_widget = self.root.focus_get()
|
||||
if not self._is_limit_editor(focused_widget):
|
||||
return
|
||||
if event.widget is focused_widget:
|
||||
return
|
||||
|
||||
self._limit_editors[focused_widget]()
|
||||
if not self._is_limit_editor(event.widget):
|
||||
self.root.after_idle(self._focus_window)
|
||||
|
||||
def _is_limit_editor(self, widget):
|
||||
return widget in self._limit_editors
|
||||
|
||||
def _finish_key_release(self, key):
|
||||
self._release_jobs.pop(key, None)
|
||||
self.model.set_key(key, False)
|
||||
if self.model.pressed_keys:
|
||||
self.status_var.set("Phím đang giữ: {}".format(self._active_keys_text()))
|
||||
else:
|
||||
self.status_var.set("Đã nhả phím - robot dừng")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _on_focus_out(self, _event):
|
||||
self.root.after_idle(self._clear_if_window_unfocused)
|
||||
|
||||
def _clear_if_window_unfocused(self):
|
||||
if not self._closed and self.root.focus_displayof() is None:
|
||||
self._clear_motion("Cửa sổ mất focus - robot dừng")
|
||||
|
||||
def _active_keys_text(self):
|
||||
return ", ".join(sorted(self.model.pressed_keys)) or "none"
|
||||
|
||||
@staticmethod
|
||||
def _quantize(value, step):
|
||||
return round(float(value) / step) * step
|
||||
|
||||
def _on_keyboard_speed_slider(self, speed_type, value):
|
||||
if self._updating_velocity_controls:
|
||||
return
|
||||
|
||||
if speed_type == "linear":
|
||||
speed = self._quantize(value, self.model.linear_step)
|
||||
self.model.set_linear_speed(speed)
|
||||
else:
|
||||
speed = self._quantize(value, self.model.angular_step)
|
||||
self.model.set_angular_speed(speed)
|
||||
self.status_var.set("Đã cập nhật tốc độ phím/joystick")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _adjust_keyboard_speed(self, speed_type, direction):
|
||||
if speed_type == "linear":
|
||||
self.model.adjust_linear_speed(direction)
|
||||
else:
|
||||
self.model.adjust_angular_speed(direction)
|
||||
self.status_var.set("Đã tăng/giảm tốc độ phím/joystick")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _on_velocity_slider(self, speed_type, value):
|
||||
if self._updating_velocity_controls:
|
||||
return
|
||||
|
||||
if speed_type == "linear":
|
||||
command = self._quantize(value, self.model.linear_step)
|
||||
self.model.set_manual_command(linear_x=command)
|
||||
if abs(command) >= self.model.min_linear_speed:
|
||||
self.model.set_linear_speed(abs(command))
|
||||
else:
|
||||
command = self._quantize(value, self.model.angular_step)
|
||||
self.model.set_manual_command(angular_z=command)
|
||||
if abs(command) >= self.model.min_angular_speed:
|
||||
self.model.set_angular_speed(abs(command))
|
||||
|
||||
self.status_var.set("Điều khiển trực tiếp bằng slider kiểu rqt")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _adjust_velocity_command(self, speed_type, direction):
|
||||
linear_x, angular_z = self.model.command()
|
||||
if speed_type == "linear":
|
||||
linear_x += float(direction) * self.model.linear_step
|
||||
self.model.set_manual_command(linear_x=linear_x)
|
||||
if abs(linear_x) >= self.model.min_linear_speed:
|
||||
self.model.set_linear_speed(abs(linear_x))
|
||||
else:
|
||||
angular_z += float(direction) * self.model.angular_step
|
||||
self.model.set_manual_command(angular_z=angular_z)
|
||||
if abs(angular_z) >= self.model.min_angular_speed:
|
||||
self.model.set_angular_speed(abs(angular_z))
|
||||
self.status_var.set("Đã tăng/giảm lệnh vận tốc")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _zero_velocity_axis(self, speed_type):
|
||||
if speed_type == "linear":
|
||||
self.model.set_manual_command(linear_x=0.0)
|
||||
else:
|
||||
self.model.set_manual_command(angular_z=0.0)
|
||||
self.status_var.set("Đã đưa {} về 0".format(speed_type))
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _apply_limit_value(self, speed_type, bound):
|
||||
try:
|
||||
if speed_type == "linear":
|
||||
if bound == "max":
|
||||
value = self._quantize(
|
||||
self.max_linear_speed_var.get(), self.model.linear_step
|
||||
)
|
||||
value = self._clamp_ui_limit(
|
||||
value, 0.0, self._linear_limit_ceiling
|
||||
)
|
||||
self.model.set_max_linear_speed(value)
|
||||
else:
|
||||
value = self._quantize(
|
||||
self.min_linear_command_var.get(), self.model.linear_step
|
||||
)
|
||||
value = self._clamp_ui_limit(
|
||||
value, -self._linear_limit_ceiling, 0.0
|
||||
)
|
||||
self.model.set_min_linear_command(value)
|
||||
elif bound == "max":
|
||||
value = self._quantize(
|
||||
self.max_angular_speed_var.get(), self.model.angular_step
|
||||
)
|
||||
value = self._clamp_ui_limit(
|
||||
value, 0.0, self._angular_limit_ceiling
|
||||
)
|
||||
self.model.set_max_angular_speed(value)
|
||||
else:
|
||||
value = self._quantize(
|
||||
self.min_angular_command_var.get(), self.model.angular_step
|
||||
)
|
||||
value = self._clamp_ui_limit(
|
||||
value, -self._angular_limit_ceiling, 0.0
|
||||
)
|
||||
self.model.set_min_angular_command(value)
|
||||
except (tk.TclError, TypeError, ValueError):
|
||||
self.status_var.set("Giới hạn không hợp lệ - đã giữ giá trị cũ")
|
||||
self._refresh_view()
|
||||
return
|
||||
|
||||
self.status_var.set("Đã cập nhật giới hạn min/max")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
@staticmethod
|
||||
def _clamp_ui_limit(value, minimum, maximum):
|
||||
return max(minimum, min(float(value), maximum))
|
||||
|
||||
def _reset_speeds(self):
|
||||
self.model.set_max_linear_speed(self._default_max_linear_speed)
|
||||
self.model.set_max_angular_speed(self._default_max_angular_speed)
|
||||
self.model.set_min_linear_command(self._default_min_linear_command)
|
||||
self.model.set_min_angular_command(self._default_min_angular_command)
|
||||
self.model.set_linear_speed(self._default_linear_speed)
|
||||
self.model.set_angular_speed(self._default_angular_speed)
|
||||
self.model.clear_motion()
|
||||
self.status_var.set("Đã khôi phục giới hạn mặc định và dừng robot")
|
||||
self._refresh_view()
|
||||
self._publish_stop()
|
||||
|
||||
def _on_joystick_drag(self, event):
|
||||
dx = float(event.x - self.JOYSTICK_CENTER)
|
||||
dy = float(event.y - self.JOYSTICK_CENTER)
|
||||
distance = math.hypot(dx, dy)
|
||||
if distance > self.KNOB_TRAVEL:
|
||||
scale = self.KNOB_TRAVEL / distance
|
||||
dx *= scale
|
||||
dy *= scale
|
||||
|
||||
for job in self._release_jobs.values():
|
||||
self.root.after_cancel(job)
|
||||
self._release_jobs.clear()
|
||||
self.model.clear_keys()
|
||||
self.model.set_joystick(dx / self.KNOB_TRAVEL, dy / self.KNOB_TRAVEL)
|
||||
self.status_var.set("Điều khiển bằng joystick")
|
||||
self._refresh_view()
|
||||
self._publish_current()
|
||||
|
||||
def _on_joystick_release(self, _event):
|
||||
self.model.release_joystick()
|
||||
self.status_var.set("Đã nhả joystick - robot dừng")
|
||||
self._refresh_view()
|
||||
self._publish_stop()
|
||||
|
||||
def _emergency_stop(self):
|
||||
self._clear_motion("STOP - đã xóa lệnh chuyển động")
|
||||
self._focus_window()
|
||||
|
||||
def _clear_motion(self, status):
|
||||
for job in self._release_jobs.values():
|
||||
self.root.after_cancel(job)
|
||||
self._release_jobs.clear()
|
||||
self.model.clear_motion()
|
||||
self.status_var.set(status)
|
||||
self._refresh_view()
|
||||
self._publish_stop()
|
||||
|
||||
def _refresh_view(self):
|
||||
linear_x, angular_z = self.model.command()
|
||||
self.linear_speed_var.set("{:+.2f} m/s".format(linear_x))
|
||||
self.angular_speed_var.set("{:+.2f} rad/s".format(angular_z))
|
||||
self.keyboard_linear_speed_var.set(
|
||||
"{:.2f} m/s".format(self.model.linear_speed)
|
||||
)
|
||||
self.keyboard_angular_speed_var.set(
|
||||
"{:.2f} rad/s".format(self.model.angular_speed)
|
||||
)
|
||||
self.max_linear_speed_var.set("{:.2f}".format(self.model.max_linear_speed))
|
||||
self.min_linear_command_var.set(
|
||||
"{:.2f}".format(self.model.min_linear_command)
|
||||
)
|
||||
self.max_angular_speed_var.set("{:.2f}".format(self.model.max_angular_speed))
|
||||
self.min_angular_command_var.set(
|
||||
"{:.2f}".format(self.model.min_angular_command)
|
||||
)
|
||||
|
||||
if self._speed_controls:
|
||||
self._updating_velocity_controls = True
|
||||
try:
|
||||
keyboard_linear = self._speed_controls["keyboard_linear"]
|
||||
keyboard_linear["scale"].configure(
|
||||
from_=self.model.min_linear_speed,
|
||||
to=self.model.max_linear_speed,
|
||||
)
|
||||
keyboard_linear["scale_var"].set(self.model.linear_speed)
|
||||
|
||||
keyboard_angular = self._speed_controls["keyboard_angular"]
|
||||
keyboard_angular["scale"].configure(
|
||||
from_=self.model.min_angular_speed,
|
||||
to=self.model.max_angular_speed,
|
||||
)
|
||||
keyboard_angular["scale_var"].set(self.model.angular_speed)
|
||||
|
||||
linear_control = self._speed_controls["linear"]
|
||||
linear_control["scale"].configure(
|
||||
from_=self.model.max_linear_speed,
|
||||
to=self.model.min_linear_command,
|
||||
)
|
||||
linear_control["scale_var"].set(linear_x)
|
||||
|
||||
angular_control = self._speed_controls["angular"]
|
||||
angular_control["scale"].configure(
|
||||
from_=self.model.max_angular_speed,
|
||||
to=self.model.min_angular_command,
|
||||
)
|
||||
angular_control["scale_var"].set(angular_z)
|
||||
finally:
|
||||
self._updating_velocity_controls = False
|
||||
|
||||
self.command_var.set(
|
||||
"linear.x {:+.2f}\nangular.z {:+.2f}".format(linear_x, angular_z)
|
||||
)
|
||||
|
||||
horizontal, vertical = self.model.joystick_position()
|
||||
knob_x = self.JOYSTICK_CENTER + horizontal * self.KNOB_TRAVEL
|
||||
knob_y = self.JOYSTICK_CENTER + vertical * self.KNOB_TRAVEL
|
||||
radius = self.KNOB_RADIUS
|
||||
self.canvas.coords(
|
||||
self.knob,
|
||||
knob_x - radius,
|
||||
knob_y - radius,
|
||||
knob_x + radius,
|
||||
knob_y + radius,
|
||||
)
|
||||
joystick_in_use = self.model.pressed_keys or self.model.joystick_active
|
||||
knob_color = "#22c55e" if joystick_in_use else "#94a3b8"
|
||||
self.canvas.itemconfigure(self.knob, fill=knob_color)
|
||||
|
||||
def _twist_from_model(self):
|
||||
linear_x, angular_z = self.model.command()
|
||||
message = Twist()
|
||||
message.linear.x = linear_x
|
||||
message.angular.z = angular_z
|
||||
return message
|
||||
|
||||
def _publish_current(self):
|
||||
if not rospy.is_shutdown():
|
||||
self.publisher.publish(self._twist_from_model())
|
||||
|
||||
def _publish_stop(self):
|
||||
try:
|
||||
self.publisher.publish(Twist())
|
||||
except (AttributeError, rospy.ROSException):
|
||||
pass
|
||||
|
||||
def _publish_tick(self):
|
||||
if self._closed:
|
||||
return
|
||||
if rospy.is_shutdown():
|
||||
self._closed = True
|
||||
self.root.destroy()
|
||||
return
|
||||
self._publish_current()
|
||||
self.root.after(self._publish_period_ms, self._publish_tick)
|
||||
|
||||
def _request_shutdown(self):
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self.model.clear_motion()
|
||||
self._publish_stop()
|
||||
rospy.signal_shutdown("Virtual joystick window closed")
|
||||
self.root.destroy()
|
||||
|
||||
def run(self):
|
||||
self.root.mainloop()
|
||||
|
||||
|
||||
def main():
|
||||
rospy.init_node("virtual_joystick_teleop")
|
||||
try:
|
||||
app = VirtualJoystickApp()
|
||||
except (ValueError, tk.TclError) as exc:
|
||||
rospy.logfatal("Cannot start virtual joystick: %s", exc)
|
||||
return
|
||||
app.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
12
setup.py
Normal file
12
setup.py
Normal file
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from catkin_pkg.python_setup import generate_distutils_setup
|
||||
from setuptools import setup
|
||||
|
||||
|
||||
setup_args = generate_distutils_setup(
|
||||
packages=["virtual_joystick_teleop"],
|
||||
package_dir={"": "src"},
|
||||
)
|
||||
|
||||
setup(**setup_args)
|
||||
5
src/virtual_joystick_teleop/__init__.py
Normal file
5
src/virtual_joystick_teleop/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
"""Keyboard teleoperation model and ROS GUI node support."""
|
||||
|
||||
from .teleop_model import TeleopModel
|
||||
|
||||
__all__ = ["TeleopModel"]
|
||||
Binary file not shown.
269
src/virtual_joystick_teleop/teleop_model.py
Normal file
269
src/virtual_joystick_teleop/teleop_model.py
Normal file
@@ -0,0 +1,269 @@
|
||||
"""ROS-independent state model for keyboard teleoperation."""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
class TeleopModel:
|
||||
"""Tracks pressed keys and converts them into differential-drive commands."""
|
||||
|
||||
SUPPORTED_KEYS = frozenset(("Up", "Down", "Left", "Right"))
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
linear_speed=0.30,
|
||||
angular_speed=0.70,
|
||||
linear_step=0.05,
|
||||
angular_step=0.10,
|
||||
min_linear_speed=0.05,
|
||||
max_linear_speed=2.00,
|
||||
min_angular_speed=0.10,
|
||||
max_angular_speed=2.00,
|
||||
min_linear_command=None,
|
||||
min_angular_command=None,
|
||||
):
|
||||
self._validate_range(
|
||||
"linear speed", min_linear_speed, max_linear_speed, linear_step
|
||||
)
|
||||
self._validate_range(
|
||||
"angular speed", min_angular_speed, max_angular_speed, angular_step
|
||||
)
|
||||
self._validate_finite("linear_speed", linear_speed)
|
||||
self._validate_finite("angular_speed", angular_speed)
|
||||
|
||||
if min_linear_command is None:
|
||||
min_linear_command = -float(max_linear_speed)
|
||||
if min_angular_command is None:
|
||||
min_angular_command = -float(max_angular_speed)
|
||||
self._validate_command_range(
|
||||
"linear command", min_linear_command, max_linear_speed
|
||||
)
|
||||
self._validate_command_range(
|
||||
"angular command", min_angular_command, max_angular_speed
|
||||
)
|
||||
|
||||
self.linear_step = float(linear_step)
|
||||
self.angular_step = float(angular_step)
|
||||
self.min_linear_speed = float(min_linear_speed)
|
||||
self.max_linear_speed = float(max_linear_speed)
|
||||
self.min_angular_speed = float(min_angular_speed)
|
||||
self.max_angular_speed = float(max_angular_speed)
|
||||
self.min_linear_command = float(min_linear_command)
|
||||
self.min_angular_command = float(min_angular_command)
|
||||
self.linear_speed = self._clamp(
|
||||
float(linear_speed), self.min_linear_speed, self.max_linear_speed
|
||||
)
|
||||
self.angular_speed = self._clamp(
|
||||
float(angular_speed), self.min_angular_speed, self.max_angular_speed
|
||||
)
|
||||
self._pressed_keys = set()
|
||||
self._joystick_axes = None
|
||||
self._manual_command = None
|
||||
|
||||
@staticmethod
|
||||
def _validate_finite(name, value):
|
||||
try:
|
||||
numeric_value = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError("{} must be a finite number".format(name)) from exc
|
||||
if not math.isfinite(numeric_value):
|
||||
raise ValueError("{} must be a finite number".format(name))
|
||||
|
||||
@classmethod
|
||||
def _validate_range(cls, name, minimum, maximum, step):
|
||||
cls._validate_finite("minimum {}".format(name), minimum)
|
||||
cls._validate_finite("maximum {}".format(name), maximum)
|
||||
cls._validate_finite("{} step".format(name), step)
|
||||
if float(minimum) < 0.0:
|
||||
raise ValueError("minimum {} must be non-negative".format(name))
|
||||
if float(maximum) < float(minimum):
|
||||
raise ValueError("maximum {} must not be less than its minimum".format(name))
|
||||
if float(step) <= 0.0:
|
||||
raise ValueError("{} step must be positive".format(name))
|
||||
|
||||
@staticmethod
|
||||
def _clamp(value, minimum, maximum):
|
||||
return max(minimum, min(value, maximum))
|
||||
|
||||
@classmethod
|
||||
def _validate_command_range(cls, name, minimum, maximum):
|
||||
cls._validate_finite("minimum {}".format(name), minimum)
|
||||
cls._validate_finite("maximum {}".format(name), maximum)
|
||||
if float(minimum) > 0.0:
|
||||
raise ValueError("minimum {} must be zero or negative".format(name))
|
||||
if float(maximum) < 0.0:
|
||||
raise ValueError("maximum {} must be zero or positive".format(name))
|
||||
if float(minimum) >= float(maximum):
|
||||
raise ValueError("minimum {} must be less than its maximum".format(name))
|
||||
|
||||
@property
|
||||
def pressed_keys(self):
|
||||
return frozenset(self._pressed_keys)
|
||||
|
||||
@property
|
||||
def joystick_active(self):
|
||||
return self._joystick_axes is not None
|
||||
|
||||
@property
|
||||
def manual_control_active(self):
|
||||
return self._manual_command is not None
|
||||
|
||||
def set_key(self, key, is_pressed):
|
||||
"""Set one arrow key state. Returns False for unsupported keys."""
|
||||
if key not in self.SUPPORTED_KEYS:
|
||||
return False
|
||||
if is_pressed:
|
||||
self.release_manual_control()
|
||||
self._pressed_keys.add(key)
|
||||
else:
|
||||
self._pressed_keys.discard(key)
|
||||
return True
|
||||
|
||||
def clear_keys(self):
|
||||
self._pressed_keys.clear()
|
||||
|
||||
def set_joystick(self, horizontal, vertical):
|
||||
"""Set analog display axes in [-1, 1] from a mouse/touch joystick."""
|
||||
self._validate_finite("joystick horizontal axis", horizontal)
|
||||
self._validate_finite("joystick vertical axis", vertical)
|
||||
self._joystick_axes = (
|
||||
self._clamp(float(horizontal), -1.0, 1.0),
|
||||
self._clamp(float(vertical), -1.0, 1.0),
|
||||
)
|
||||
self.release_manual_control()
|
||||
|
||||
def release_joystick(self):
|
||||
self._joystick_axes = None
|
||||
|
||||
def clear_motion(self):
|
||||
self.clear_keys()
|
||||
self.release_joystick()
|
||||
self.release_manual_control()
|
||||
|
||||
def set_manual_command(self, linear_x=None, angular_z=None):
|
||||
"""Set a persistent signed command, as used by rqt-style sliders."""
|
||||
if self._manual_command is None:
|
||||
current_linear, current_angular = self.command()
|
||||
else:
|
||||
current_linear, current_angular = self._manual_command
|
||||
|
||||
if linear_x is not None:
|
||||
self._validate_finite("manual linear command", linear_x)
|
||||
current_linear = float(linear_x)
|
||||
if angular_z is not None:
|
||||
self._validate_finite("manual angular command", angular_z)
|
||||
current_angular = float(angular_z)
|
||||
|
||||
self.clear_keys()
|
||||
self.release_joystick()
|
||||
self._manual_command = self._clamp_command(
|
||||
current_linear, current_angular
|
||||
)
|
||||
return self._manual_command
|
||||
|
||||
def release_manual_control(self):
|
||||
self._manual_command = None
|
||||
|
||||
def _clamp_command(self, linear_x, angular_z):
|
||||
return (
|
||||
self._clamp(
|
||||
float(linear_x), self.min_linear_command, self.max_linear_speed
|
||||
),
|
||||
self._clamp(
|
||||
float(angular_z), self.min_angular_command, self.max_angular_speed
|
||||
),
|
||||
)
|
||||
|
||||
def _clamp_manual_command(self):
|
||||
if self._manual_command is not None:
|
||||
self._manual_command = self._clamp_command(*self._manual_command)
|
||||
|
||||
def command(self):
|
||||
"""Return (linear_x [m/s], angular_z [rad/s])."""
|
||||
if self._manual_command is not None:
|
||||
return self._manual_command
|
||||
|
||||
if self._joystick_axes is not None:
|
||||
horizontal, vertical = self._joystick_axes
|
||||
return self._clamp_command(
|
||||
-vertical * self.linear_speed,
|
||||
-horizontal * self.angular_speed,
|
||||
)
|
||||
|
||||
linear_axis = int("Up" in self._pressed_keys) - int(
|
||||
"Down" in self._pressed_keys
|
||||
)
|
||||
angular_axis = int("Left" in self._pressed_keys) - int(
|
||||
"Right" in self._pressed_keys
|
||||
)
|
||||
return self._clamp_command(
|
||||
linear_axis * self.linear_speed,
|
||||
angular_axis * self.angular_speed,
|
||||
)
|
||||
|
||||
def joystick_position(self):
|
||||
"""Return display axes in the range [-1, 1] for the virtual stick."""
|
||||
if self._joystick_axes is not None:
|
||||
return self._joystick_axes
|
||||
horizontal = int("Right" in self._pressed_keys) - int(
|
||||
"Left" in self._pressed_keys
|
||||
)
|
||||
vertical = int("Down" in self._pressed_keys) - int(
|
||||
"Up" in self._pressed_keys
|
||||
)
|
||||
return horizontal, vertical
|
||||
|
||||
def adjust_linear_speed(self, direction):
|
||||
return self.set_linear_speed(
|
||||
self.linear_speed + float(direction) * self.linear_step
|
||||
)
|
||||
|
||||
def adjust_angular_speed(self, direction):
|
||||
return self.set_angular_speed(
|
||||
self.angular_speed + float(direction) * self.angular_step
|
||||
)
|
||||
|
||||
def set_linear_speed(self, value):
|
||||
self._validate_finite("linear speed", value)
|
||||
self.linear_speed = self._clamp(
|
||||
float(value), self.min_linear_speed, self.max_linear_speed
|
||||
)
|
||||
return self.linear_speed
|
||||
|
||||
def set_angular_speed(self, value):
|
||||
self._validate_finite("angular speed", value)
|
||||
self.angular_speed = self._clamp(
|
||||
float(value), self.min_angular_speed, self.max_angular_speed
|
||||
)
|
||||
return self.angular_speed
|
||||
|
||||
def set_max_linear_speed(self, value):
|
||||
self._validate_finite("maximum linear speed", value)
|
||||
self.max_linear_speed = max(self.min_linear_speed, float(value))
|
||||
self.linear_speed = min(self.linear_speed, self.max_linear_speed)
|
||||
self._clamp_manual_command()
|
||||
return self.max_linear_speed
|
||||
|
||||
def set_max_angular_speed(self, value):
|
||||
self._validate_finite("maximum angular speed", value)
|
||||
self.max_angular_speed = max(self.min_angular_speed, float(value))
|
||||
self.angular_speed = min(self.angular_speed, self.max_angular_speed)
|
||||
self._clamp_manual_command()
|
||||
return self.max_angular_speed
|
||||
|
||||
def set_min_linear_command(self, value):
|
||||
self._validate_finite("minimum linear command", value)
|
||||
self.min_linear_command = min(0.0, float(value))
|
||||
if self.min_linear_command >= self.max_linear_speed:
|
||||
self.min_linear_command = min(0.0, self.max_linear_speed - self.linear_step)
|
||||
self._clamp_manual_command()
|
||||
return self.min_linear_command
|
||||
|
||||
def set_min_angular_command(self, value):
|
||||
self._validate_finite("minimum angular command", value)
|
||||
self.min_angular_command = min(0.0, float(value))
|
||||
if self.min_angular_command >= self.max_angular_speed:
|
||||
self.min_angular_command = min(
|
||||
0.0, self.max_angular_speed - self.angular_step
|
||||
)
|
||||
self._clamp_manual_command()
|
||||
return self.min_angular_command
|
||||
159
test/test_teleop_model.py
Executable file
159
test/test_teleop_model.py
Executable file
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import unittest
|
||||
|
||||
from virtual_joystick_teleop import TeleopModel
|
||||
|
||||
|
||||
class TeleopModelTest(unittest.TestCase):
|
||||
def test_arrow_keys_create_expected_twist_components(self):
|
||||
model = TeleopModel(linear_speed=0.3, angular_speed=0.7)
|
||||
|
||||
model.set_key("Up", True)
|
||||
model.set_key("Left", True)
|
||||
|
||||
self.assertEqual((0.3, 0.7), model.command())
|
||||
self.assertEqual((-1, -1), model.joystick_position())
|
||||
|
||||
def test_opposite_keys_cancel_each_axis(self):
|
||||
model = TeleopModel(linear_speed=0.3, angular_speed=0.7)
|
||||
for key in TeleopModel.SUPPORTED_KEYS:
|
||||
model.set_key(key, True)
|
||||
|
||||
self.assertEqual((0.0, 0.0), model.command())
|
||||
|
||||
def test_release_and_clear_stop_motion(self):
|
||||
model = TeleopModel()
|
||||
model.set_key("Down", True)
|
||||
self.assertLess(model.command()[0], 0.0)
|
||||
|
||||
model.set_key("Down", False)
|
||||
self.assertEqual((0.0, 0.0), model.command())
|
||||
|
||||
model.set_key("Right", True)
|
||||
model.clear_motion()
|
||||
self.assertEqual((0.0, 0.0), model.command())
|
||||
|
||||
def test_analog_joystick_scales_and_clamps_commands(self):
|
||||
model = TeleopModel(linear_speed=0.4, angular_speed=0.8)
|
||||
|
||||
model.set_joystick(-0.5, -0.25)
|
||||
|
||||
self.assertEqual((0.1, 0.4), model.command())
|
||||
self.assertEqual((-0.5, -0.25), model.joystick_position())
|
||||
self.assertTrue(model.joystick_active)
|
||||
|
||||
model.set_joystick(5.0, -5.0)
|
||||
self.assertEqual((0.4, -0.8), model.command())
|
||||
|
||||
model.release_joystick()
|
||||
self.assertFalse(model.joystick_active)
|
||||
self.assertEqual((0.0, 0.0), model.command())
|
||||
|
||||
def test_speed_buttons_clamp_to_configured_limits(self):
|
||||
model = TeleopModel(
|
||||
linear_speed=0.2,
|
||||
angular_speed=0.4,
|
||||
linear_step=0.1,
|
||||
angular_step=0.2,
|
||||
min_linear_speed=0.1,
|
||||
max_linear_speed=0.3,
|
||||
min_angular_speed=0.2,
|
||||
max_angular_speed=0.6,
|
||||
)
|
||||
|
||||
for _ in range(10):
|
||||
model.adjust_linear_speed(1)
|
||||
model.adjust_angular_speed(-1)
|
||||
|
||||
self.assertAlmostEqual(0.3, model.linear_speed)
|
||||
self.assertAlmostEqual(0.2, model.angular_speed)
|
||||
|
||||
def test_speed_sliders_set_and_clamp_values(self):
|
||||
model = TeleopModel(
|
||||
linear_speed=0.2,
|
||||
angular_speed=0.4,
|
||||
max_linear_speed=2.0,
|
||||
max_angular_speed=3.0,
|
||||
)
|
||||
|
||||
self.assertAlmostEqual(1.6, model.set_linear_speed(1.6))
|
||||
self.assertAlmostEqual(2.5, model.set_angular_speed(2.5))
|
||||
self.assertAlmostEqual(2.0, model.set_linear_speed(10.0))
|
||||
self.assertAlmostEqual(3.0, model.set_angular_speed(10.0))
|
||||
|
||||
def test_runtime_limit_change_clamps_current_speed(self):
|
||||
model = TeleopModel(
|
||||
linear_speed=1.5,
|
||||
angular_speed=2.5,
|
||||
max_linear_speed=3.0,
|
||||
max_angular_speed=4.0,
|
||||
)
|
||||
|
||||
self.assertAlmostEqual(1.0, model.set_max_linear_speed(1.0))
|
||||
self.assertAlmostEqual(1.0, model.linear_speed)
|
||||
self.assertAlmostEqual(2.0, model.set_max_angular_speed(2.0))
|
||||
self.assertAlmostEqual(2.0, model.angular_speed)
|
||||
|
||||
self.assertAlmostEqual(
|
||||
model.min_linear_speed,
|
||||
model.set_max_linear_speed(-1.0),
|
||||
)
|
||||
|
||||
def test_rqt_style_manual_command_is_signed_and_persistent(self):
|
||||
model = TeleopModel(
|
||||
max_linear_speed=2.0,
|
||||
max_angular_speed=3.0,
|
||||
min_linear_command=-1.0,
|
||||
min_angular_command=-2.0,
|
||||
)
|
||||
|
||||
model.set_manual_command(linear_x=-0.7)
|
||||
model.set_manual_command(angular_z=1.4)
|
||||
|
||||
self.assertTrue(model.manual_control_active)
|
||||
self.assertEqual((-0.7, 1.4), model.command())
|
||||
self.assertEqual((-0.7, 1.4), model.command())
|
||||
|
||||
model.clear_motion()
|
||||
self.assertFalse(model.manual_control_active)
|
||||
self.assertEqual((0.0, 0.0), model.command())
|
||||
|
||||
def test_manual_command_and_keyboard_are_clamped_to_signed_limits(self):
|
||||
model = TeleopModel(
|
||||
linear_speed=2.0,
|
||||
angular_speed=3.0,
|
||||
max_linear_speed=2.0,
|
||||
max_angular_speed=3.0,
|
||||
min_linear_command=-0.8,
|
||||
min_angular_command=-1.5,
|
||||
)
|
||||
|
||||
model.set_manual_command(linear_x=-10.0, angular_z=10.0)
|
||||
self.assertEqual((-0.8, 3.0), model.command())
|
||||
|
||||
model.set_key("Down", True)
|
||||
model.set_key("Right", True)
|
||||
self.assertEqual((-0.8, -1.5), model.command())
|
||||
|
||||
model.set_min_linear_command(-0.4)
|
||||
model.set_min_angular_command(-0.5)
|
||||
self.assertEqual((-0.4, -0.5), model.command())
|
||||
|
||||
def test_invalid_speed_configuration_is_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
TeleopModel(min_linear_speed=1.0, max_linear_speed=0.5)
|
||||
with self.assertRaises(ValueError):
|
||||
TeleopModel(angular_step=0.0)
|
||||
with self.assertRaises(ValueError):
|
||||
TeleopModel(min_linear_command=0.5)
|
||||
|
||||
def test_unsupported_key_does_not_change_state(self):
|
||||
model = TeleopModel()
|
||||
|
||||
self.assertFalse(model.set_key("space", True))
|
||||
self.assertEqual((0.0, 0.0), model.command())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user