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.
This commit is contained in:
2026-09-22 15:32:00 +07:00
parent 4d0ade7c6d
commit 6c9f77eaae
7 changed files with 98 additions and 13 deletions

View File

@@ -25,7 +25,10 @@ follow the layout and interaction pattern of `rqt_robot_steering`, and the node
Multiple arrow keys can be held together. For example, Up + Left commands Multiple arrow keys can be held together. For example, Up + Left commands
forward motion while turning left. Dragging the joystick provides proportional forward motion while turning left. Dragging the joystick provides proportional
control up to the configured speed. Keyboard and joystick inputs stop when they 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 are released. While a non-zero command is active it is published at the configured
rate. Releasing control publishes one zero `Twist`, then the node stays silent
until the next command so another `/cmd_vel` publisher is not overwritten.
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 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. 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 While a min/max field has focus, arrow keys only edit its number and do not

View File

@@ -8,7 +8,7 @@ from tkinter import ttk
import rospy import rospy
from geometry_msgs.msg import Twist from geometry_msgs.msg import Twist
from virtual_joystick_teleop import TeleopModel from virtual_joystick_teleop import CommandPublishGate, TeleopModel
class VirtualJoystickApp: class VirtualJoystickApp:
@@ -59,13 +59,19 @@ class VirtualJoystickApp:
) )
self._updating_velocity_controls = False self._updating_velocity_controls = False
self._limit_editors = {} self._limit_editors = {}
self._publish_gate = CommandPublishGate()
self.publisher = rospy.Publisher(self._cmd_vel_topic, Twist, queue_size=1) self.publisher = rospy.Publisher(self._cmd_vel_topic, Twist, queue_size=1)
rospy.on_shutdown(self._publish_stop) rospy.on_shutdown(self._publish_stop)
self.root = tk.Tk() # 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.title("ROS Virtual Joystick - Điều khiển robot")
self.root.resizable(False, False) 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.protocol("WM_DELETE_WINDOW", self._request_shutdown)
self.root.bind_all("<KeyPress>", self._on_key_press, add="+") self.root.bind_all("<KeyPress>", self._on_key_press, add="+")
self.root.bind_all("<KeyRelease>", self._on_key_release, add="+") self.root.bind_all("<KeyRelease>", self._on_key_release, add="+")
@@ -96,6 +102,23 @@ class VirtualJoystickApp:
raise ValueError("{} must be a positive finite number".format(name)) raise ValueError("{} must be a positive finite number".format(name))
return value 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): def _configure_style(self):
style = ttk.Style(self.root) style = ttk.Style(self.root)
if "clam" in style.theme_names(): if "clam" in style.theme_names():
@@ -740,17 +763,17 @@ class VirtualJoystickApp:
self._publish_stop() self._publish_stop()
def _emergency_stop(self): def _emergency_stop(self):
self._clear_motion("STOP - đã xóa lệnh chuyển động") self._clear_motion("STOP - đã xóa lệnh chuyển động", force_stop=True)
self._focus_window() self._focus_window()
def _clear_motion(self, status): def _clear_motion(self, status, force_stop=False):
for job in self._release_jobs.values(): for job in self._release_jobs.values():
self.root.after_cancel(job) self.root.after_cancel(job)
self._release_jobs.clear() self._release_jobs.clear()
self.model.clear_motion() self.model.clear_motion()
self.status_var.set(status) self.status_var.set(status)
self._refresh_view() self._refresh_view()
self._publish_stop() self._publish_stop(force=force_stop)
def _refresh_view(self): def _refresh_view(self):
linear_x, angular_z = self.model.command() linear_x, angular_z = self.model.command()
@@ -831,10 +854,15 @@ class VirtualJoystickApp:
return message return message
def _publish_current(self): def _publish_current(self):
if not rospy.is_shutdown(): if rospy.is_shutdown():
self.publisher.publish(self._twist_from_model()) 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): def _publish_stop(self, force=False):
if not self._publish_gate.allow_stop(force=force):
return
try: try:
self.publisher.publish(Twist()) self.publisher.publish(Twist())
except (AttributeError, rospy.ROSException): except (AttributeError, rospy.ROSException):
@@ -855,7 +883,7 @@ class VirtualJoystickApp:
return return
self._closed = True self._closed = True
self.model.clear_motion() self.model.clear_motion()
self._publish_stop() self._publish_stop(force=True)
rospy.signal_shutdown("Virtual joystick window closed") rospy.signal_shutdown("Virtual joystick window closed")
self.root.destroy() self.root.destroy()

View File

@@ -1,5 +1,5 @@
"""Keyboard teleoperation model and ROS GUI node support.""" """Keyboard teleoperation model and ROS GUI node support."""
from .teleop_model import TeleopModel from .teleop_model import CommandPublishGate, TeleopModel
__all__ = ["TeleopModel"] __all__ = ["CommandPublishGate", "TeleopModel"]

View File

@@ -3,6 +3,39 @@
import math import math
class CommandPublishGate:
"""Allow motion continuously and only one zero command on transition to idle."""
def __init__(self, zero_epsilon=1e-9):
TeleopModel._validate_finite("zero epsilon", zero_epsilon)
if float(zero_epsilon) < 0.0:
raise ValueError("zero epsilon must be non-negative")
self._zero_epsilon = float(zero_epsilon)
self._motion_was_published = False
@property
def motion_was_published(self):
return self._motion_was_published
def allow_command(self, linear_x, angular_z):
"""Return True for motion, or once when motion transitions to zero."""
TeleopModel._validate_finite("linear command", linear_x)
TeleopModel._validate_finite("angular command", angular_z)
has_motion = (
abs(float(linear_x)) > self._zero_epsilon
or abs(float(angular_z)) > self._zero_epsilon
)
should_publish = has_motion or self._motion_was_published
self._motion_was_published = has_motion
return should_publish
def allow_stop(self, force=False):
"""Consume active ownership; force allows an explicit one-shot STOP."""
should_publish = bool(force) or self._motion_was_published
self._motion_was_published = False
return should_publish
class TeleopModel: class TeleopModel:
"""Tracks pressed keys and converts them into differential-drive commands.""" """Tracks pressed keys and converts them into differential-drive commands."""

View File

@@ -2,7 +2,28 @@
import unittest import unittest
from virtual_joystick_teleop import TeleopModel from virtual_joystick_teleop import CommandPublishGate, TeleopModel
class CommandPublishGateTest(unittest.TestCase):
def test_idle_is_silent_after_exactly_one_zero_transition(self):
gate = CommandPublishGate()
self.assertFalse(gate.allow_command(0.0, 0.0))
self.assertTrue(gate.allow_command(0.3, 0.0))
self.assertTrue(gate.allow_command(0.3, 0.0))
self.assertTrue(gate.allow_command(0.0, 0.0))
self.assertFalse(gate.allow_command(0.0, 0.0))
self.assertFalse(gate.allow_command(0.0, 0.0))
def test_stop_is_once_unless_explicitly_forced(self):
gate = CommandPublishGate()
gate.allow_command(0.0, 0.7)
self.assertTrue(gate.allow_stop())
self.assertFalse(gate.allow_stop())
self.assertTrue(gate.allow_stop(force=True))
self.assertFalse(gate.allow_stop())
class TeleopModelTest(unittest.TestCase): class TeleopModelTest(unittest.TestCase):