Welcome to DOFBOT-Ultra repository
7. AI Butler-Garbage Sorting
AI Butler-Garbage Sorting
Please ensure that the web control program backend process is not running in the background. To close it, refer to the [Get Started Quickly - 2. Access the Terminal] section in [Disable the Auto-Start Web Control Backend Process]. After closing, please restart DofbotUltra!!!
Before running this function, you need to close the web control program backend process. For the closing method, refer to the [4. Preparation] section [1. Manage Web control services].
1. Function Description
After the program starts, give the large model a garbage sorting instruction. After thinking, the large model will control the robotic arm to sort the garbage label code blocks on the table as instructed.
2. Startup
Taking the text version as an example, Raspberry Pi (DofbotUltra) users can directly open a terminal and enter the following command:
ros2 launch largemodel largemodel_control.launch.py text_chat_mode:=True
Then open a second terminal and enter the following command:
xxxxxxxxxxros2 run text_chat text_chat
Garbage sorting has the following types of instructions:
Sort a single type of garbage: e.g., sort toxic waste
Leave a certain type of garbage: e.g., sort all garbage except recyclables
Sort all garbage on the table: e.g., clean up all garbage on the table
2.1. Sort a Single Type of Garbage
2.1.1. Startup
Enter the following in the text_chat terminal:
xClean up toxic garbage
Press Enter. For the voice version, wake up the voice module and directly say "Clean up toxic garbage." Wait for the large model to think and reply, as shown below:

The robotic arm will pick up the toxic waste label code block on the table.
2.1.2. Task Planning
Call garbage_sort('tox') to sort toxic waste.
2.1.3. Core Source Code Analysis
The garbage_sort function, source located at:
Raspberry Pi: /home/yahboom/dofbot_ultra_ws/src/llm/largemodel/largemodel/action_service.py
RDK: /home/sunrise/dofbot_ultra_ws/src/llm/largemodel/largemodel/action_service.py
xxxxxxxxxxdef garbage_sort(self, type_): Arm.Arm_serial_servo_write6(90,120,10,10,90,30,1000) time.sleep(1.0) type_ = type_.strip("'\"") # Strip single and double quotes if type_ == "rec": target_type_ = float(1) elif type_ == "tox": target_type_ = float(2) elif type_ == "wet": target_type_ = float(3) elif type_ == "dry": target_type_ = float(4) else: self.get_logger().info( "Fatal ERROR:Incorrect type_ input,Does the AI output not meet expectations?" ) self.action_status_pub( "garbage_sort_failed", type_=type_ ) return # Start the robotic arm grasping program cmd1 = "ros2 run dofbot_ultra_yolov11 yolov11_sortation" # Start the image conversion program cmd2 = "ros2 run dofbot_ultra_yolov11 msgToimg" # Start the garbage recognition program cmd3 = f"ros2 run largemodel_arm yolov11_ALM --ros-args -p target_type:={target_type_:.1f}" subprocess.Popen( [ "gnome-terminal", "--title=grasp_desktop_garbage_sort", "--", "bash", "-c", f"{cmd1}; exec bash", ] ) subprocess.Popen( [ "gnome-terminal", "+--title=detect_img", "--", "bash", "-c", f"{cmd2}; exec bash", ] ) subprocess.Popen( [ "gnome-terminal", "--title=garbage_detect", "--", "bash", "-c", f"{cmd3}; exec bash", ] ) RDK: /home/sunrise/dofbot_ultra_ws/src/llm/largemodel/largemodel/action_service.py
x def garbage_sort(self, type_): self.pub_arm(list(OBS_JOINTS), runtime=1000) time.sleep(1.0) type_ = type_.strip("'\"") # Strip single and double quotes if type_ == "rec": target_type_ = 1 elif type_ == "tox": target_type_ = 2 elif type_ == "wet": target_type_ = 3 elif type_ == "dry": target_type_ = 4 else: self.get_logger().info( "Fatal ERROR:Incorrect type_ input,Does the AI output not meet expectations?" ) self.action_status_pub( "garbage_sort_failed", type_=type_ ) return cmd1 = "ros2 run largemodel_arm grasp" cmd2 = f"ros2 run largemodel_arm yolov11_garbage --ros-args -p target_type:={target_type_:.1f}" subprocess.Popen(cmd1, shell=True) subprocess.Popen(cmd2, shell=True)
while not self.garbage_sort_future.done(): if self.interrupt_flag: self.check_garbage_sort() self.pub_arm(list(OBS_JOINTS), runtime=1000) return time.sleep(0.1)
result = self.garbage_sort_future.result() self.check_garbage_sort() if not self.interrupt_flag: if result.data == "garbage_sort_done": self.action_status_pub( "garbage_sort_done", type_=type_ ) elif result.data == "garbage_sort_no_found": self.action_status_pub( "garbage_sort_no_found" ) self.garbage_sort_future = Future() # Reset Future objectLet's mainly analyze the garbage recognition program yolov11_ALM. Source path:
Raspberry Pi: /home/yahboom/dofbot_ultra_ws/src/llm/largemodel_arm/largemodel_arm/yolov11_ALM.py
xxxxxxxxxx# Get the garbage type to be sorted via command line parametersself.declare_parameter('target_type', 1.0)self.TargetType = int(self.get_parameter('target_type').get_parameter_value().double_value)# Based on the value of self.TargetType, modify self.waste, which contains all garbage names of that typeif self.TargetType == 1: self.waste = ['Newspaper','Zip_top_can','Book','Old_school_bag']elif self.TargetType == 2: self.waste = ['Syringe','Expired_cosmetics','Used_batteries','Expired_tablets']elif self.TargetType == 3: self.waste = ['Fish_bone','Egg_shell','Apple_core','Watermelon_rind']elif self.TargetType == 4: self.waste = ['Toilet_paper','Peach_pit','Cigarette_butts','Disposable_chopsticks'] # Initialize a YOLO object detection model instance, load the precompiled TensorRT engine file (best.engine), and specify the model task type as detection (detect)self.yolo_model = YOLO("/home/pi/dofbot_ultra_ws/src/dofbot_ultra_yolov11/dofbot_ultra_yolov11/best.engine", task='detect')# Create a subscriber to subscribe to the converted image data topicself.image_sub = self.create_subscription(ImageMsg,"/image_data",self.image_sub_callback,qos_profile=1)
# In the callback function image_sub_callback# Use YOLO11 for object detectionresults = self.yolo_model(self.img, save=False, verbose=False) boxes = results[0].boxes# Iterate through the detection resultsfor box in boxes: # detections per image x_min, y_min, x_max, y_max = map(int, box.xyxy[0]) class_id = int(box.cls) confidence = float(box.conf) label = f"{self.yolo_model.names[class_id]} {confidence:.2f}" # Calculate the center position center_x = (x_min + x_max) // 2 center_y = (y_min + y_max) // 2 # Extract the information of the currently detected label code and assign it to center, including the center point coordinates and the label code name center = Yolov11Detect() center.centerx = float(center_x) center.centery = float(center_y) center.result = str(self.yolo_model.names[class_id]) # If the currently detected label code name is in the self.waste list, it is the target sorting object. Publish the sorting flag and the position information of the label code. if center.result in self.waste: start_flag = Bool() start_flag.data = True self.pub_SortFlag.publish(start_flag) self.detect_flag = True self.cnt = self.cnt + 1 print("Found the target.") self.pubDetect.publish(center) self.start_flag = FalseRDK: /home/sunrise/dofbot_ultra_ws/src/llm/largemodel_arm/largemodel_arm/yolov11_ALM.py
xxxxxxxxxx # ---------- Target category mapping (model output name => whether it is a target) ---------- # Note: Use the string actually output by the model (first letter capitalized, connected by underscores) self.target_waste = { 1: ['Newspaper', 'Zip_top_can', 'Book', 'Old_school_bag'], 2: ['Syringe', 'Expired_cosmetics', 'Used_batteries', 'Expired_tablets'], 3: ['Fish_bone', 'Egg_shell', 'Apple_core', 'Watermelon_rind'], 4: ['Toilet_paper', 'Peach_pit', 'Cigarette_butts', 'Disposable_chopsticks'] } self.waste_list = self.target_waste.get(self.target_type, []) if not self.waste_list: self.get_logger().warn(f'Invalid target_type {self.target_type}, will detect nothing')
# ---------- YOLO Model ---------- self.yolo_model = YOLO(self.model_path, task='detect')
# ---------- Publish / Subscribe ---------- # Compatible with BPU node interface self.pos_info_pub = self.create_publisher(AprilTagInfo, '/PosInfo', 10) self.grasp_enable_pub = self.create_publisher(Bool, '/grasp_enable', 10) self.largemodel_arm_done_pub = self.create_publisher(String, '/largemodel_arm_done', 1)
# Grasp completion feedback self.grasp_done_sub = self.create_subscription(Bool, '/grasp_done', self._grasp_done_callback, 10)
# Image subscription (topic name /image_data can be kept, or changed to /camera/color/image_raw, configurable via parameters) self.image_sub = self.create_subscription(Image, '/image_data', self._image_callback, 10)
# ---------- State Variables ---------- self.initial_wait_done = False # Whether the startup wait period has passed self.detection_enabled = False # Whether to allow detection of new targets self.start_time = time.time() # Node startup time self.grasp_count = 0 # Number of successful grasps self.node_done = False # Overall task completion flag self.waiting_grasp = False # Whether waiting for grasp completion self.grasp_wait_timer = None # Grasp wait timeout timer
# Visualization related self._last_time = None
self.get_logger().info('YOLOv11 Compatible Node started (BPU interface)')RDK recognition analysis program: /home/sunrise/dofbot_ultra_ws/src/llm/largemodel_arm/largemodel_arm/yolov11_garbage.py
xxxxxxxxxx # Target category sets self.target_sets = { 1: {'newspaper', 'zip-top-can', 'book', 'school-bag'}, 2: {'syringe', 'cosmetics', 'tablets', 'batteries'}, 3: {'fish-bone', 'egg-shell', 'apple-core', 'watermelon-rind'}, 4: {'toilet-paper', 'peach-pit', 'cigarette-butts', 'disposable-chopsticks'} } self._target_names = self.target_sets.get(self.target_type, set()) self._target_names_norm = {normalize_name(n) for n in self._target_names}
self.rgb_bridge = CvBridge() self.depth_bridge = CvBridge()
# Publish / Subscribe self.pos_info_pub = self.create_publisher(AprilTagInfo, "PosInfo", 10) self.grasp_enable_pub = self.create_publisher(Bool, "grasp_enable", 10) self.TargetJoint5_pub = self.create_publisher(Int16, "set_joint5", 10) self.largemodel_arm_done_pub = self.create_publisher(String, "/largemodel_arm_done", 1) self.grasp_done_sub = self.create_subscription(Bool, "grasp_done", self._grasp_done_callback, 1)
# Image subscriptions self.rgb_sub = Subscriber(self, Image, self.image_topic, qos_profile=qos_profile_sensor_data) if USE_DEPTH_CAMERA: self.depth_sub = Subscriber(self, Image, self.depth_topic, qos_profile=qos_profile_sensor_data) # Increase queue size and tolerance to prevent backlog self.ts = ApproximateTimeSynchronizer( [self.rgb_sub, self.depth_sub], queue_size=20, slop=0.2 ) self.ts.registerCallback(self._image_callback) else: self.depth_sub = None self.ts = None self._usb_rgb_sub = self.create_subscription( Image, self.image_topic, self._on_usb_image, qos_profile=qos_profile_sensor_data )
# State variables self.start_time = time.time() self.waiting_grasp_done = False self.done_once = False self._sent_once = False self._last_vis = None self._bridge_pr_time = time.time() self._last_pos_msg = None self._last_joint5 = None self._burst_timer = None self._burst_remaining = 0 self._burst_interval_s = 0.2 # Increased from 0.05 to reduce publish frequency self._burst_count = 2 # Reduced repeat count self._grasp_wait_timer = None
# Thread pool for inference timeout self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self.get_logger().info("YOLOv11 Garbage Detection Node Started (Stability Optimized)")2.2. Leave a Certain Type of Garbage
2.1.1. Startup
Enter the following in the text_chat terminal:
xIn addition to the wet waste on the desktop, clear away other types of waste from the surface.
Press Enter. If it's a voice version, wake up the voice module and directly say "In addition to the wet waste on the desktop, clear away other types of waste from the surface." to the voice module. Wait for the large model to think and reply, as shown in the figure below,

Except for the recyclable garbage label code blocks, the robotic arm will pick up other types of garbage label code blocks on the table.
2.2.2. Task Planning
Call the garbage sorting function garbage_sort(x) sequentially, with parameters 'tox', 'wet', and 'dry'. Only one action function can be output at a time.
Task steps:
Call
garbage_sort('tox')Call
garbage_sort('wet')Call
garbage_sort('dry')
2.3. Sort All Garbage on the Table
2.3.1. Startup
Enter the following in the text_chat terminal:
xClean up all garbage on the desktop
Press Enter. For the voice version, wake up the voice module and directly say "Clean up all garbage on the table." Wait for the large model to think and reply, as shown below:

The robotic arm will sort all garbage label blocks on the table.
2.3.2. Task Planning
Call the garbage_sort_all() function.