yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
Muto RS Robot📖
01.Introduction to Muto Robot
  • 1.Accessories introduction
  • 2.Precautions for battery
  • 3.FAQ
  • 4.MutoRS Study Guide
  • 5.Quick Start Guide
02.Assembly and write system
  • 1.Raspberry Pi write system
  • 2.Assembly video
03.Remote control course
  • 1.Open and Close APP Control Program
  • 2.Mobile APP Remote Control
  • 3.USB Wireless Controller Remote Control
  • 4.Web Host Computer Remote Control
04.Remote login operation
  • 1.SSH and VNC remote login
  • 2.Jupyter Lab login and running example code
05.AI Large Model Basicsnew
  • 1.AI Large Model Types and Principles
  • 2.RAG Retrieval Enhancement and Model Training Samples
  • 3.Embodied Intelligent Robot System Architecture
  • 4.Embodied Intelligent Functions Core Source Code
06.AI Large Model Developmentnew
  • 1.Register a model service provider account
  • 2.Configure API-KEY
  • 3.Introduction to Dify
  • 4.Dify Basic function
  • 5.AI large model development - Chatbot
  • 6.Deploy the RAG knowledge base
  • 7.RAG knowledge base + Chatbot
  • 8.AI agent workflow
  • 9.Custom wake-up response
  • 10.Core module testing tools
07.AI Large Model (Text Version)new
  • 0.MutoRS Model Setup & Details
  • 1.Semantic Understanding, Instruction Following
  • 2.Multimodal Visual Understanding
  • 3.Multimodal Visual Understanding + Depth Camera Distance Q&A
  • 4.Multimodal Visual Understanding + Visual Line Following
  • 5.Multimodal Visual Understanding + Visual Following
  • 6.Multimodal Visual Understanding + SLAM Navigation
  • 7.Multimodal Visual Understanding + SLAM Navigation + Visual Line Following
  • 8.Intention Estimation + Multimodal Visual Understanding + SLAM Navigation + Visual Functions
08.AI Large Model (Voice Version)new
  • 0.MutoRS Model Setup & Details
  • 1.Semantic Understanding, Instruction Following
  • 2.Multimodal Visual Understanding
  • 3.Multimodal Visual Understanding + Depth Camera Distance Q&A
  • 4.Multimodal Visual Understanding + Visual Line Following
  • 5.Multimodal Visual Understanding + Visual Following
  • 6.Multimodal Visual Understanding + SLAM Navigation
  • 7.Multimodal Visual Understanding + SLAM Navigation + Visual Line Following
  • 8.Intention Estimation + Multimodal Visual Understanding + SLAM Navigation + Visual Functions
09.AI Large Model (Fun Applications)new
  • 1.Versatile performer
  • 2.Action Imitation
  • 3.Problem Solving Expert
  • 4.Exploring Unfamiliar Environments
10.Robot basic course
  • 1)Control buzzer
  • 2)Control PWM servo
  • 3)Control bus servo
  • 4)Robot forward and backward
  • 5)Robot move left and right
  • 6)Robot rotate left and right
  • 7)Control height
  • 8)Control head
  • 9)Action group performance
  • 10)Read data
  • 11)Host computer control
  • 12)Camera driver
11.Voice control coursenew
  • 1.Control Muto motion
  • 2.Control Muto tracking
  • 3.Control Muto color recognition
  • 4.Control Muto color tracking
  • 5.Control multi-point navigation
12.AI vision course
  • 0)Color HSV Calibration
  • 1)Color recognition
  • 2)Color following
  • 3)Color recognition action group
  • 4)Face detection
  • 5)QR code recognition
  • 6)QR code instructions
  • 7)Visual line following
  • 8)Motion learning
  • 9)Synchronous action teaching
13.Mediapipe course
  • 1)Hand detection
  • 2)Attitude detection
  • 3)Overall inspection
  • 4)Face detection
  • 5)Face recognition
  • 6)Face effects
  • 7)Face detection
  • 8)3D object recognition
  • 9)Brush
  • 10)Finger control
  • 11)Gesture recognition
14.Depth camera course
  • 1)Depth camera use
  • 2)Internal reference calibration
  • 3)Web page real-time monitoring
  • 4)ROS+opencv application
  • 5)QR code creation and recognition
  • 6)AR vision
  • 7)Tracking
  • 8)Obstacle recognition
  • 9)Color tracking
  • 10)KCF object tracking
  • 11)RTAB-Map 3D mapping navigation
15.Lidar course
  • 1)About lidar
  • 2)Lidar obstacle avoidance
  • 3)Lidar tracking
  • 4)Lidar guard
  • 5)Patrol
  • 6)SLAM overview
  • 7)ROS2_Gmapping mapping algorithm
  • 8)ROS2_Cartographer mapping algorithm
  • 9)About ROS2 Navigation
  • 10)ROS2 navigation and avoid
  • 11) APP mapping
  • 12)APP navigation
16.Road network navigationnew
  • 1.Road network planning and navigation environment deployment
  • 2.Constructing pose maps
  • 3.Road network annotation
  • 4.Inter-road network planning and navigation
  • 5.Road network navigation under arbitrary poses
  • 6.Path replanning
17.Multi-machine control course
  • 1)Multi-vehicle control
  • 2)Multi-vehicle navigation
18.Robot chassis control
  • 1)Hexapod gait and kinematics
  • 2)Robot information release
  • 3)Robot control
  • 4)URDF model
19.Raspberry Pi course
  • 1)Python usage
  • 2)Use APT to install Python packages
  • 3)Python virtual environment
  • 4)GPIO Zero
  • 5)Pin output high and low levels
  • 6)Pin reads high and low levels
  • 7)Pin output PWM
  • 8)Serial communication
  • 9)I2C communication
20.OpenCV course
  • 1)Introduction to Open Source CV
  • 2)Image reading and display
  • 3)Picture writing
  • 4)Image Quality
  • 5)Pixel operations
  • 6)Image zoom
  • 7)Picture cut
  • 8)Picture pan
  • 9)Picture mirroring
  • 10)Affine transformation
  • 11)Picture rotation
  • 12)perspective transformation
  • 13)Grayscale processing
  • 14)Binary image
  • 15)Edge green detection
  • 16)Line segment drawing
  • 17)Rectangular circle drawing
  • 18)Text and picture drawing
21.Docker course
  • 1)Overview and installation
  • 2)Common commands
  • 3)Deeply understand and publish images
  • 4)Hardware interaction and data processing
  • 5)Enter docker container
  • 6)Robot development environment construction
  • 7)Update docker images
22.ROS2 basic course
  • 1) Introduction to ROS2
  • 2)ROS2 install Humble
  • 3)ROS2 development environment
  • 4)ROS2 workspace
  • 5)ROS2 function package
  • 6)ROS2 node
  • 7)ROS2 topic communication
  • 8)ROS2 service communication
  • 9)ROS2 action communication
  • 10)ROS2 custom interface message
  • 11)ROS2 parameter service case
  • 12)ROS2 meta-function package
  • 13)ROS2 distributed communication
  • 14)ROS2 DDS
  • 15)ROS2 time related API
  • 16)ROS2 common command tools
  • 17)ROS2 rviz2 use
  • 18)ROS2 rqt toolbox
  • 19)ROS2 Launch startup file configuration
  • 20)ROS2 recording and playback tool
  • 21)ROS2 URDF model
  • 22)ROS2 Gazebo simulation platform
  • 23)ROS2 TF2 coordinate transformation
23.Linux basic course
  • 1)Introduction to Linux system
  • 2)Ubuntu file system
  • 3)Ubuntu common commands
  • 4)Ubuntu common editors
  • 5)Ubuntu software operation commands
  • 6)Virtual machine installation
  • 7)SSH remote control
  • 8)VNC remote control
  • 9)Driver library and communication
  • 10)Static IP and hotspot mode
  • 11)Bind device ID
  • 12)Capacity expansion and resource allocation
  • 13)Back up system image
  • 14)Update system software sources
  • 15)Set root user password
  • 16)sudo free password
  • 17)Connect to WiFi network
  • 18)View system version
  • 19)Customized service management
  • 20.Back up system image
24.Mainboard Large Model Course
Offline large model (Text Interaction)
  • 0. AI large model image description
  • 1. Deployment of large AI model environments
  • 2. Installation of large model dialogue platform
  • 3. Meta AI Llama 3.2 model
  • 4. Alibaba Cloud Qwen3 Model
  • 5. Microsoft Phi-4-mini model
  • 6. DeepSeek DeepSeek-R1 model
  • 7. Alibaba Cloud Qwen2.5vl Visual Multimodal Large Model
  • 8. Google Gemma3 Visual Multimodal Large Model
  • 9. Llava Visual Multimodal Large Model
  • 10. MiniCPM-V Visual Multimodal Large Model
  • 11. Multimodal Visual Understanding Applications
  • 12. Multimodal Text-Based Image Application
  • 13. Multimodal Video Analysis Application
  • 14. Multimodal visual positioning applications
  • 15. Multimodal table scanning application
  • 16. Multimodal Autonomous Agent Application
Offline large model (Voice Interaction)
  • 0. Voice Interaction Hardware Connection (Must Read)
  • 1. Offline speech-to-text (ASR)
  • 2. Offline Text-to-Speech (TTS)
  • 3. AI large model voice interaction
  • 4. Multimodal visual understanding and voice interaction
  • 5. Multimodal Text-Based Image Application
  • 6. Multimodal Video Analysis Application
  • 7. Multimodal visual positioning applications
  • 8. Multimodal table scanning application
  • 9. Multimodal Autonomous Agent Applications
  • 10. AI large model offline voice assistant
Online large model (text interaction)
  • 1.OpenRouter Large Model API Aggregation Platform
  • 2. Multimodal Visual Understanding Applications
  • 3. Multimodal visual positioning applications
  • 4. Multimodal table scanning application
  • 5. Multimodal Autonomous Agent Applications
Online large model (voice interaction)
  • 0. Voice Interaction Hardware Connection (Must Read)
  • 1. Online speech-to-text (ASR)
  • 2. Online Text-to-Speech (TTS)
  • 3. AI large model voice interaction
  • 4. Multimodal visual and voice interaction
  • 5. Multimodal visual positioning applications
  • 6. Multimodal table scanning application
  • 7. Multimodal Autonomous Agent Applications
  • 8. AI large model online voice assistant
Download
  • RemoteCtrl_APP(iOS/Android)
  • Mapping_APP(iOS_Android)
  • SystemFile_For_RPi5
  • SystemFile_Jetson
  • SystemFile_RPi
  • Code
  • VM File
  • Hardware Info
  • Instruction Manual
  • Jetson_Boot_USB.tar.gz
  • ROS2_Basic_VM
Download ZIP

Welcome to Muto RS Robot repository

3.Multimodal Visual Understanding + Depth Camera Distance Q&A

3. Multimodal Visual Understanding + Depth Camera Distance Question Answering

3. Multimodal Visual Understanding + Depth Camera Distance Question AnsweringIntroductionOperation StepsPreparatory StepsGetting StartedUsage EffectCode SummarySupplement: Radar Ranging

Introduction

In this tutorial, we will learn how to issue commands via chat with Muto in the Dify interface.

Operation Steps

Preparatory Steps

This lesson requires that the Dify terminal be launched beforehand, and all configuration items have been configured as in the previous section.

image-20260107192230750

image-20251219175135071

image-20260121163833

image-20251219175918681


This lesson requires MutoRS to be powered on. Following the steps in the previous chapters, start the large model terminal in Docker.

image-20251219161400133

image-20251219161725029


In this tutorial, we will use a plain text version of the large model, starting it with the --no-voice parameter. Using the --no-voice parameter eliminates the risk of being interrupted by external voice prompts during use!

x
cd muto-llm-2.0/ && ./rebuild_and_launch.sh --no-voice

image-20251219174910627

Getting Started

For the large text model, you need to enter Muto's IP address here, which is the address used to access the Dify page.

image-20251231143529040

In this tutorial section, we will integrate the large model into our depth camera.

Usage Effect

The command used in this section is: "See if there's a can of Coca-Cola in front of you. If there is, see how far away it is."

The effect is as follows:

image-20251219205336977

You can change the object to query according to the actual scenario.

Code Summary

The key function used in this section is:

xxxxxxxxxx
get_depth_at_point(x, y): Gets the distance (in meters) at the specified coordinates (x, y) in the depth camera image. It needs to be used in conjunction with the results of visual recognition.

This function is defined in the path \packages\muto_hexapod_lib\muto_hexapod_lib\Largemodel\sensor_manager.py

The core code is as follows:

xxxxxxxxxx
    def get_depth_at_point(self, x: int, y: int, timeout_s: float = 5.0) -> tuple:
        """
        获取指定坐标点的深度信息(智能节点管理)
        Get depth information at specified coordinates (with intelligent node management)
        
        Args:
            x: 图像中的x坐标 X coordinate in the image
            y: 图像中的y坐标 Y coordinate in the image
            timeout_s: 超时时间(秒) Timeout in seconds
            
        Returns:
            tuple: (success: bool, message: str, data: dict)
                success: 执行是否成功 Whether execution was successful
                message: 执行结果消息 Execution result message
                data: 深度信息 Depth information
        """
        depth_topic = "/camera/depth/image_raw"
        
        try:
            # Intelligent Node Management: Check Camera Initial Status
            camera_was_running = False
            camera_started_by_us = False
            
            camera_success, camera_msg, camera_data = self.get_camera_status()
            camera_was_running = camera_success and camera_data.get('status') == 'running'
            
            # If the camera is not running, start the camera first.
            if not camera_was_running:
                start_success, start_msg, start_data = self.start_camera(wait_time_s=5.0)
                if not start_success:
                    return False, f"无法启动相机 Failed to start camera: {start_msg}", {
                        "x": x,
                        "y": y,
                        "camera_start_attempted": True,
                        "camera_start_success": False,
                        "error": "camera_start_failed"
                    }
                camera_started_by_us = True
            
           # Execute core depth acquisition function
            # 开始获取坐标点的深度信息 Starting to get depth info at point
            # 深度话题 Depth topic
            
            # Check necessary dependencies
            try:
                import rclpy
                from rclpy.node import Node
                from sensor_msgs.msg import Image
                from cv_bridge import CvBridge
                import cv2
                import numpy as np
                # 所有必要依赖可用 All required dependencies available
            except ImportError as import_error:
                # 缺少必要依赖 Missing required dependencies
                # 请安装: pip install opencv-python
                # Please install: pip install opencv-python
                return False, f"缺少必要依赖 Missing required dependencies: {str(import_error)}", {"x": x, "y": y, "error": "missing_dependencies"}
            
           # Create a depth image capture node
            import uuid
            depth_node_id = str(uuid.uuid4())[:8]  # Use the first 8 digits of the UUID as the unique identifier
            
            class DepthCaptureNode(Node):
                def __init__(self):
                    super().__init__(f'depth_capture_node_{depth_node_id}')
                    self.bridge = CvBridge()
                    self.depth_received = False
                    self.depth_image = None
                    self.subscription = self.create_subscription(
                        Image,
                        depth_topic,
                        self.depth_callback,
                        10
                    )
                    # 已订阅深度话题 Subscribed to depth topic
                
                def depth_callback(self, msg):
                    try:
                        # Convert ROS depth image messages to OpenCV images
                        # Depth images are typically 16-bit single-channel images
                        depth_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough")
                        self.depth_image = depth_image
                        self.depth_received = True
                        # 成功接收深度图像 Successfully received depth image
                    except Exception as e:
                        print(f"深度图像转换失败 Depth image conversion failed: {str(e)}")
                        # 深度图像转换失败 Depth image conversion failed
            
            # Initialize ROS2 (if it has not been initialized yet)
            if not rclpy.ok():
                rclpy.init()
            
            # Create nodes and wait for depth image
            node = DepthCaptureNode()
            
            # 等待深度图像数据 Waiting for depth image data
            
            # Waiting for depth image data - Add error handling and retry mechanism
            start_time = time.time()
            spin_retry_count = 0
            max_spin_retries = 3
            
            while not node.depth_received and (time.time() - start_time) < timeout_s:
                try:
                    rclpy.spin_once(node, timeout_sec=0.1)
                    spin_retry_count = 0  # Reset retry count
                except Exception as spin_error:
                    spin_retry_count += 1
                    error_msg = str(spin_error)
                    
                   # Check if it's an "event index too big" error.
                    if "event index too big" in error_msg or "index" in error_msg.lower():
                        if spin_retry_count <= max_spin_retries:
                            print(f"⚠️ ROS2事件循环错误 (深度获取重试 {spin_retry_count}/{max_spin_retries}): {error_msg}")
                            time.sleep(0.2)  # Retry after a short delay
                            continue
                        else:
                            print(f"❌ ROS2事件循环错误超过最大重试次数 (深度获取): {error_msg}")
                            node.destroy_node()
                            return False, f"ROS2事件循环错误 (深度获取): {error_msg}", {"x": x, "y": y, "error": "ros2_event_loop_error_depth"}
                    else:
                        # Other types of errors
                        print(f"❌ ROS2 spin_once错误 (深度获取): {error_msg}")
                        node.destroy_node()
                        return False, f"ROS2 spin_once错误 (深度获取): {error_msg}", {"x": x, "y": y, "error": "ros2_spin_error_depth"}
            
            if node.depth_received and node.depth_image is not None:
                # Check if the coordinates are within the image range
                height, width = node.depth_image.shape[:2]
                
                if x < 0 or x >= width or y < 0 or y >= height:
                    # 坐标超出图像范围 Coordinates out of image bounds
                    # 图像尺寸 Image size
                    # 请求坐标 Requested coordinates
                    node.destroy_node()
                    return False, f"坐标超出图像范围 Coordinates out of bounds: ({x}, {y}), image size: {width}x{height}", {
                        "x": x, "y": y, 
                        "image_width": width, 
                        "image_height": height,
                        "error": "coordinates_out_of_bounds"
                    }
                
                # Get the depth value of a specified coordinate point
                depth_value = node.depth_image[y, x]
                
               # Depth values are usually expressed in millimeters, which can be converted to meters.
                if node.depth_image.dtype == np.uint16:
                   # 16-bit depth image, typically in millimeters
                    depth_meters = float(depth_value) / 1000.0
                    depth_mm = float(depth_value)
                elif node.depth_image.dtype == np.float32:
                   # 32-bit floating-point depth image, usually in meters
                    depth_meters = float(depth_value)
                    depth_mm = float(depth_value) * 1000.0
                else:
                    # Other formats, assuming millimeters are the unit
                    depth_meters = float(depth_value) / 1000.0
                    depth_mm = float(depth_value)
                
                # Check if the depth value is valid (0 usually indicates an invalid depth).
                is_valid = bool(depth_value > 0)  # Convert to Python's native bool type
                
                # 深度信息获取成功 Depth information retrieved successfully
                # 坐标 Coordinates
                # 原始深度值 Raw depth value
                # 深度(米) Depth (meters)
                # 深度(毫米) Depth (millimeters)
                # 数据类型 Data type
                # 有效性 Valid
                
                # Obtain depth information of the surrounding area (3x3 region)
                surrounding_depths = []
                for dy in range(-1, 2):
                    for dx in range(-1, 2):
                        nx, ny = x + dx, y + dy
                        if 0 <= nx < width and 0 <= ny < height:
                            surrounding_depth = node.depth_image[ny, nx]
                            if node.depth_image.dtype == np.uint16:
                                surrounding_depth_m = float(surrounding_depth) / 1000.0
                            elif node.depth_image.dtype == np.float32:
                                surrounding_depth_m = float(surrounding_depth)
                            else:
                                surrounding_depth_m = float(surrounding_depth) / 1000.0
                            surrounding_depths.append({
                                "x": nx, "y": ny, 
                                "depth_raw": float(surrounding_depth),
                                "depth_meters": surrounding_depth_m,
                                "valid": bool(surrounding_depth > 0)  # Convert to Python's native bool type
                            })
                
                # Clean up nodes
                node.destroy_node()
                
                # Intelligent Node Management: If it's a camera we started, close it after execution.
                if camera_started_by_us:
                    try:
                        self.stop_camera(wait_time_s=1.0)
                    except Exception as stop_error:
                        print(f"⚠️ 自动关闭相机警告: {stop_error}")
                
                return True, "深度信息获取成功 Depth information retrieved successfully", {
                    "x": x,
                    "y": y,
                    "depth_raw": float(depth_value),
                    "depth_meters": depth_meters,
                    "depth_millimeters": depth_mm,
                    "is_valid": is_valid,
                    "image_size": {"width": width, "height": height},
                    "data_type": str(node.depth_image.dtype),
                    "surrounding_area": surrounding_depths,
                    "method": "cv_bridge_depth",
                    "camera_auto_managed": camera_started_by_us
                }
            else:
                # 深度图像获取超时 Depth image capture timeout
                # 请检查深度相机是否正常发布数据 Please check if depth camera is publishing data normally
                node.destroy_node()
                
                # Intelligent Node Management: If it's a camera we started, close it after execution.
                if camera_started_by_us:
                    try:
                        self.stop_camera(wait_time_s=1.0)
                    except Exception as stop_error:
                        print(f"⚠️ 自动关闭相机警告: {stop_error}")
                
                return False, f"深度图像获取超时 Depth image capture timeout ({timeout_s}s)", {
                    "x": x, "y": y, 
                    "timeout": timeout_s, 
                    "suggestion": "check_depth_camera_publishing",
                    "camera_auto_managed": camera_started_by_us
                }
                
        except Exception as e:
            # 深度信息获取过程中发生错误 Error during depth information retrieval
            # Intelligent Node Management: If it's a camera we started, close it after execution.
            if camera_started_by_us:
                try:
                    self.stop_camera(wait_time_s=1.0)
                except Exception as stop_error:
                    print(f"⚠️ 自动关闭相机警告: {stop_error}")
            
            return False, f"深度信息获取过程中发生错误 Error during depth information retrieval: {str(e)}", {
                "x": x, "y": y, 
                "error": str(e),
                "camera_auto_managed": camera_started_by_us
            }

 

Supplement: Radar Ranging

Besides using a depth camera, the Muto can also perform 360-degree ranging using its built-in LiDAR. Before using this function, the LiDAR needs to be configured (see 0. MutoRS Dedicated Large Model Configuration and Related Content Instructions).

The prompt is as follows:

"Please scan the environment with the LiDAR to see how far away the obstacle is directly in front of you."

image-20260107212710765

image-20260107212736569

The core code is as follows:

xxxxxxxxxx
    def get_lidar_data(self, timeout_s: float = 5.0, sample_count: int = 1) -> tuple:
        """
        读取雷达节点数据 (智能节点管理:自动检查并启动雷达节点)
        Read lidar node data (Smart node management: automatically check and start lidar node)
        
        Args:
            timeout_s: 读取超时时间(秒) Read timeout in seconds
            sample_count: 采样次数 Number of samples to collect
            
        Returns:
            tuple: (success: bool, message: str, data: dict)
                success: 读取是否成功 Whether read was successful
                message: 读取结果消息 Read result message
                data: 雷达数据信息 Lidar data information
        
        Examples:
            success, msg, data = sensor_manager.get_lidar_data()
        """
        # Intelligent Node Management: Check radar status and activate when needed.
        lidar_started_by_us = False
        lidar_status_success, _, lidar_status_data = self.check_lidar_status()
        
        if not lidar_status_success or not lidar_status_data.get('node_running', False):
            # Radar is not running, try starting it.
            start_success, start_msg, _ = self.start_lidar(wait_time_s=3.0)
            if not start_success:
                return False, f"无法启动雷达节点 Failed to start lidar node: {start_msg}", {
                    "lidar_auto_managed": False,
                    "start_error": start_msg
                }
            lidar_started_by_us = True
        
        try:
            lidar_type = self._get_lidar_type()
            topic_name = "/scan"
            
           # Check if the topic is active
            topic_success, topic_msg, topic_data = self.check_ros2_topic_active(topic_name, "sensor_msgs/msg/LaserScan")
            if not topic_success or not topic_data.get('active', False):
                # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
                if lidar_started_by_us:
                    try:
                        self.stop_lidar(wait_time_s=1.0)
                    except Exception as stop_error:
                        print(f"⚠️ 自动关闭雷达警告: {stop_error}")
                
                return False, f"雷达话题未活跃 Lidar topic not active: {topic_name}", {
                    "lidar_type": lidar_type,
                    "topic_name": topic_name,
                    "topic_active": False,
                    "error": topic_msg,
                    "lidar_auto_managed": lidar_started_by_us
                }
            
            # Read Radar Data - Compatible with ROS2 Humble Version, Optimized Blocking Time
            # Use the `--once` parameter to obtain a complete frame of data, avoiding incomplete data due to manual truncation.
            # Add the `--full-length` parameter to ensure that array data is not omitted.
            cmd = ["ros2", "topic", "echo", "--once", "--full-length", topic_name]
            
            try:
                # Start the process using Popen
                process = subprocess.Popen(
                    cmd,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    text=True
                )
                
                # Wait for data output, using the full timeout period.
                output_lines = []
                try:
                    stdout, stderr = process.communicate(timeout=timeout_s)
                    if stdout:
                        output_lines = stdout.splitlines()
                except subprocess.TimeoutExpired:
                    process.kill()
                    # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
                    if lidar_started_by_us:
                        try:
                            self.stop_lidar(wait_time_s=1.0)
                        except Exception as stop_error:
                            print(f"⚠️ 自动关闭雷达警告: {stop_error}")
                    return False, f"读取雷达数据超时 Lidar data read timeout: {timeout_s}s", {
                        "lidar_type": lidar_type,
                        "topic_name": topic_name,
                        "data_received": False,
                        "error": "timeout",
                        "lidar_auto_managed": lidar_started_by_us
                    }
                
                # Process the acquired data
                if output_lines and len(output_lines) > 0:
                    # Analyze basic information
                    scan_info = {
                        "lidar_type": lidar_type,
                        "topic_name": topic_name,
                        "data_received": True,
                        "raw_data_length": len('\n'.join(output_lines)),
                        "timestamp": time.time(),
                        "lines_received": len(output_lines)
                    }
                    
                    # Parse the various fields of the LaserScan message
                    ranges_data = []
                    intensities_data = []
                    in_ranges_section = False
                    in_intensities_section = False
                    
                    for line in output_lines:
                        line = line.strip()
                        try:
                            # Parse header information
                            if "frame_id:" in line:
                                scan_info["frame_id"] = line.split(":")[1].strip()
                            # Analysis Angle Information
                            elif "angle_min:" in line:
                                scan_info["angle_min"] = float(line.split(":")[1].strip())
                            elif "angle_max:" in line:
                                scan_info["angle_max"] = float(line.split(":")[1].strip())
                            elif "angle_increment:" in line:
                                scan_info["angle_increment"] = float(line.split(":")[1].strip())
                            # Parse time information
                            elif "time_increment:" in line:
                                scan_info["time_increment"] = float(line.split(":")[1].strip())
                            elif "scan_time:" in line:
                                scan_info["scan_time"] = float(line.split(":")[1].strip())
                            # Analyze distance range
                            elif "range_min:" in line:
                                scan_info["range_min"] = float(line.split(":")[1].strip())
                            elif "range_max:" in line:
                                scan_info["range_max"] = float(line.split(":")[1].strip())
                            # Start checking the ranges array
                            elif line == "ranges:":
                                in_ranges_section = True
                                in_intensities_section = False
                           # Start checking the intensities array
                            elif line == "intensities:":
                                in_intensities_section = True
                                in_ranges_section = False
                            # Parse ranges data
                            elif in_ranges_section and line.startswith("- "):
                                try:
                                    value_str = line[2:].strip()  # Remove the "-" prefix
                                    if value_str == ".inf":
                                        # Convert infinity values to maximum measurement range values to avoid JSON serialization errors.
                                        ranges_data.append(scan_info.get("range_max", 30.0))
                                    elif value_str == "-.inf":
                                        # Convert negative infinity to the minimum measurement range value
                                        ranges_data.append(scan_info.get("range_min", 0.0))
                                    elif value_str == "nan":
                                        # Convert NaN values to 0 to indicate invalid measurements.
                                        ranges_data.append(0.0)
                                    else:
                                        value = float(value_str)
                                        # Check if it is a valid floating-point number
                                        if value != value or value == float('inf') or value == float('-inf'):
                                            ranges_data.append(0.0)  # Convert invalid values to 0
                                        else:
                                            ranges_data.append(value)
                                except ValueError:
                                    continue
                           # Parse intensities data
                            elif in_intensities_section and line.startswith("- "):
                                try:
                                    value_str = line[2:].strip()  # Remove the "-" prefix
                                    if value_str == ".inf" or value_str == "-.inf" or value_str == "nan":
                                        # Convert invalid strength values to 0 to avoid JSON serialization errors.
                                        intensities_data.append(0.0)
                                    else:
                                        value = float(value_str)
                                        # Check if it is a valid floating-point number
                                        if value != value or value == float('inf') or value == float('-inf'):
                                            intensities_data.append(0.0)  # Convert invalid values to 0
                                        else:
                                            intensities_data.append(value)
                                except ValueError:
                                    continue
                           # Stop parsing the current array when other fields are detected
                            elif line.endswith(":") and not line.startswith("- "):
                                in_ranges_section = False
                                in_intensities_section = False
                        except (ValueError, IndexError):
                            continue  # Ignore lines with parsing errors
                    
                    # Add parsed array data
                    if ranges_data:
                        scan_info["ranges"] = ranges_data
                        scan_info["ranges_count"] = len(ranges_data)
                        # Calculate the statistics of valid distance data (excluding 0 values, as 0 indicates an invalid measurement).
                        valid_ranges = [r for r in ranges_data if r > 0.0 and r != float('inf') and r != float('-inf') and r == r]  # Exclude inf, nan and 0 values
                        if valid_ranges:
                            scan_info["valid_ranges_count"] = len(valid_ranges)
                            scan_info["min_range"] = min(valid_ranges)
                            scan_info["max_range"] = max(valid_ranges)
                            scan_info["avg_range"] = sum(valid_ranges) / len(valid_ranges)
                        else:
                            scan_info["valid_ranges_count"] = 0
                    
                    if intensities_data:
                        scan_info["intensities"] = intensities_data
                        scan_info["intensities_count"] = len(intensities_data)
                    
                   # Generate sample_points (angle-distance pairs)
                    if "angle_min" in scan_info and "angle_increment" in scan_info and ranges_data:
                        sample_points = []
                        angle_min = scan_info["angle_min"]
                        angle_increment = scan_info["angle_increment"]
                        
                        for i, range_val in enumerate(ranges_data):
                            angle = angle_min + i * angle_increment
                            sample_points.append({
                                "angle": angle,
                                "distance": range_val,
                                "intensity": intensities_data[i] if i < len(intensities_data) else 0.0
                            })
                        
                        scan_info["sample_points"] = sample_points
                    else:
                        # If critical data is missing, create empty sample_points to maintain compatibility.
                        scan_info["sample_points"] = []
                        scan_info["data_incomplete"] = True
                        scan_info["missing_fields"] = []
                        if "angle_min" not in scan_info:
                            scan_info["missing_fields"].append("angle_min")
                        if "angle_increment" not in scan_info:
                            scan_info["missing_fields"].append("angle_increment")
                        if not ranges_data:
                            scan_info["missing_fields"].append("ranges_data")
                    
                    # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
                    if lidar_started_by_us:
                        try:
                            self.stop_lidar(wait_time_s=1.0)
                        except Exception as stop_error:
                            print(f"⚠️ 自动关闭雷达警告: {stop_error}")
                    
                   # Add automatic management of status to returned data
                    scan_info["lidar_auto_managed"] = lidar_started_by_us
                    
                    return True, f"成功读取雷达数据 Successfully read lidar data: {lidar_type}", scan_info
                else:
                    # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
                    if lidar_started_by_us:
                        try:
                            self.stop_lidar(wait_time_s=1.0)
                        except Exception as stop_error:
                            print(f"⚠️ 自动关闭雷达警告: {stop_error}")
                    
                    return False, f"雷达数据为空 Empty lidar data: {topic_name}", {
                        "lidar_type": lidar_type,
                        "topic_name": topic_name,
                        "data_received": False,
                        "error": "empty_data",
                        "lidar_auto_managed": lidar_started_by_us
                    }
                    
            except Exception as e:
                # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
                if lidar_started_by_us:
                    try:
                        self.stop_lidar(wait_time_s=1.0)
                    except Exception as stop_error:
                        print(f"⚠️ 自动关闭雷达警告: {stop_error}")
                
                return False, f"读取雷达数据出错 Error reading lidar data: {str(e)}", {
                    "lidar_type": lidar_type,
                    "topic_name": topic_name,
                    "data_received": False,
                    "error": str(e),
                    "lidar_auto_managed": lidar_started_by_us
                }
                
        except subprocess.TimeoutExpired:
           # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
            if lidar_started_by_us:
                try:
                    self.stop_lidar(wait_time_s=1.0)
                except Exception as stop_error:
                    print(f"⚠️ 自动关闭雷达警告: {stop_error}")
            
            return False, f"读取雷达数据超时 Lidar data read timeout: {timeout_s}s", {
                "lidar_type": lidar_type,
                "topic_name": topic_name,
                "data_received": False,
                "error": "timeout",
                "lidar_auto_managed": lidar_started_by_us
            }
        except Exception as e:
           # Intelligent Node Management: If it's a radar system we initiated, shut it down after execution.
            if lidar_started_by_us:
                try:
                    self.stop_lidar(wait_time_s=1.0)
                except Exception as stop_error:
                    print(f"⚠️ 自动关闭雷达警告: {stop_error}")
            
            return False, f"读取雷达数据出错 Error reading lidar data: {str(e)}", {
                "lidar_type": lidar_type,
                "error": str(e),
                "lidar_auto_managed": lidar_started_by_us
            }

 

Multimodal Visual Understanding
Multimodal Visual Understanding + Visual Line Following

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文