Files
virtual_joystick_teleop/scripts/virtual_joystick_node.py
duongtd 6c9f77eaae feat: CommandPublishGate - chi publish mot lenh zero Twist khi tha dieu khien, them icon cua so
Truoc: publish lien tuc kha ca zero Twist theo timer -> de ghi de /cmd_vel cua publisher khac
khi joystick khong dieu khien. CommandPublishGate: lenh khac-zero publish binh thuong theo chu
ky; ve zero thi publish DUNG MOT LAN roi im, chi publish lai khi co lenh khac-zero moi.
UI: dat className "VirtualJoystickTeleop" cho WM_CLASS (truoc dung chung "Tk" voi moi app Tk
khac, bi gom lan trong taskbar/window picker) + ve icon joystick 32x32 khong can file ngoai.
2026-09-22 15:32:00 +07:00

906 lines
33 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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 CommandPublishGate, 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._publish_gate = CommandPublishGate()
self.publisher = rospy.Publisher(self._cmd_vel_topic, Twist, queue_size=1)
rospy.on_shutdown(self._publish_stop)
# className sets X11 WM_CLASS: without it every Tk app shares the generic
# "Tk" class, so window pickers/taskbars group and icon this the same as
# any other Tkinter tool and it gets lost among them.
self.root = tk.Tk(className="VirtualJoystickTeleop")
self.root.title("ROS Virtual Joystick - Điều khiển robot")
self.root.resizable(False, False)
self._icon_image = self._build_icon()
self.root.iconphoto(True, self._icon_image)
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 _build_icon(self, size=32):
"""Draw a small joystick-knob icon for the window/taskbar, no external file needed."""
icon = tk.PhotoImage(width=size, height=size)
bg, ring, knob = "#111827", "#1f2937", "#22c55e"
center = size / 2.0
outer_r = size * 0.46
knob_r = size * 0.22
icon.put(bg, to=(0, 0, size, size))
for y in range(size):
for x in range(size):
dist = math.hypot(x - center, y - center)
if dist <= knob_r:
icon.put(knob, (x, y))
elif dist <= outer_r:
icon.put(ring, (x, y))
return icon
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", force_stop=True)
self._focus_window()
def _clear_motion(self, status, force_stop=False):
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(force=force_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 rospy.is_shutdown():
return
message = self._twist_from_model()
if self._publish_gate.allow_command(message.linear.x, message.angular.z):
self.publisher.publish(message)
def _publish_stop(self, force=False):
if not self._publish_gate.allow_stop(force=force):
return
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(force=True)
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()