diff --git a/src/robot_bringup/CMakeLists.txt b/src/robot_bringup/CMakeLists.txt
index 0db76f2..fa26d19 100644
--- a/src/robot_bringup/CMakeLists.txt
+++ b/src/robot_bringup/CMakeLists.txt
@@ -9,6 +9,11 @@ catkin_package()
# phai build. Cai dat de dung duoc bang `rosrun robot_bringup teleop.py`.
catkin_install_python(PROGRAMS
scripts/teleop.py
+ scripts/virtual_joystick.py
+ # teleop_model.py la MODULE, khong phai node. Phai cai vao CUNG thu muc voi
+ # virtual_joystick.py vi node import no theo kieu anh em (sys.path[0] la thu
+ # muc chua script). Bo dong nay thi node chay tu devel se ImportError.
+ scripts/teleop_model.py
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
diff --git a/src/robot_bringup/launch/teleop_joystick.launch b/src/robot_bringup/launch/teleop_joystick.launch
index 19227a2..0db123d 100644
--- a/src/robot_bringup/launch/teleop_joystick.launch
+++ b/src/robot_bringup/launch/teleop_joystick.launch
@@ -1,7 +1,18 @@
-
+
@@ -75,8 +87,8 @@
-
diff --git a/src/robot_bringup/scripts/teleop_model.py b/src/robot_bringup/scripts/teleop_model.py
new file mode 100755
index 0000000..7d97889
--- /dev/null
+++ b/src/robot_bringup/scripts/teleop_model.py
@@ -0,0 +1,280 @@
+"""
+Mo hinh trang thai teleop, KHONG phu thuoc ROS.
+
+============ NGUON GOC ============
+Port tu package `virtual_joystick_teleop` (BSD-3-Clause), tac gia duongtd,
+https://git.pnkr.asia/DuongTD/virtual_joystick_teleop.git
+
+Dua vao robot_bringup de bo phu thuoc ngoai: package goc khong duoc commit
+trong workspace nay nen bi xoa la ca luong lai robot chet theo.
+Logic giu NGUYEN VEN, khong sua mot dong nao.
+"""
+
+
+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
diff --git a/src/robot_bringup/scripts/virtual_joystick.py b/src/robot_bringup/scripts/virtual_joystick.py
new file mode 100755
index 0000000..1e92739
--- /dev/null
+++ b/src/robot_bringup/scripts/virtual_joystick.py
@@ -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 teleop_model 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("", self._on_key_press, add="+")
+ self.root.bind_all("", self._on_key_release, add="+")
+ self.root.bind_all("", self._on_mouse_press, add="+")
+ self.root.bind("", 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("", self._on_joystick_drag)
+ self.canvas.bind("", self._on_joystick_drag)
+ self.canvas.bind("", 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(
+ "",
+ lambda _event: self._commit_limit_edit(callback),
+ )
+ spinbox.bind(
+ "",
+ lambda _event: self._commit_limit_edit(callback),
+ )
+ spinbox.bind("", 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()