### Quick Start Example for GO2 Robot Control Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/00-START-HERE.txt This snippet demonstrates the basic steps to initialize the SDK, connect to a GO2 robot, and perform simple movements like standing up, moving forward, and stopping. Ensure the network interface is correctly configured before running. ```python from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient import time ChannelFactoryInitialize(0, "eth0") client = SportClient() client.SetTimeout(10.0) client.Init() client.StandUp() time.sleep(1.0) client.Move(0.5, 0.0, 0.0) time.sleep(2.0) client.StopMove() ``` -------------------------------- ### Complete GO2 Robot State Client Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-robot-state-client.md A comprehensive example demonstrating initialization, service listing, service switching, and report frequency configuration using the RobotStateClient. ```python import sys from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.robot_state.robot_state_client import RobotStateClient # Initialize communication if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create and initialize client client = RobotStateClient() client.SetTimeout(5.0) client.Init() # Query all services code, services = client.ServiceList() if code == 0: print("Available services:") for svc in services: print(f" {svc.name}: {'on' if svc.status == 1 else 'off'} " f"(protected={svc.protect})") # Enable sport service code = client.ServiceSwitch("sport", True) if code == 0: print("Sport service enabled") elif code == 5202: print("Sport service is protected") # Set reporting frequency client.SetReportFreq(50, 5) # Report every 50ms for 5 seconds ``` -------------------------------- ### Complete B2 Sport Client Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/b2-sport-client.md A comprehensive example demonstrating the initialization of the SportClient, setting timeout, standing up, switching to fast walk, moving forward, stopping, and standing down. ```python import time import sys from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.b2.sport.sport_client import SportClient, PathPoint # Initialize if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create client client = SportClient() client.SetTimeout(10.0) client.Init() # Stand up client.StandUp() time.sleep(1.0) # Switch to fast walk client.FastWalk() # Move forward client.Move(0.5, 0.0, 0.0) time.sleep(2.0) # Stop client.StopMove() client.StandDown() ``` -------------------------------- ### Install Unitree SDK2 Python Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/README.md Install the SDK from source. Optionally, set the CYCLONEDDS_HOME environment variable if using a custom CycloneDDS path. ```bash cd unitree_sdk2_python pip3 install -e . # Or with specific CycloneDDS path export CYCLONEDDS_HOME=~/cyclonedds/install pip3 install -e . ``` -------------------------------- ### Initialize and Start Video Stream Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Initializes the video client, sets a timeout, and starts the front camera stream. It then subscribes to video frames and displays them, exiting on ESC key press. Includes cleanup for video client and windows. ```python import sys import cv2 import numpy as np from unitree_sdk2py.go2.video.video_client import VideoClient from unitree_sdk2py.core.channel import ChannelFactoryInitialize, ChannelSubscriber from unitree_sdk2py.idl.unitree_go.msg.dds_ import ImageFrame_ # Initialize if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create video client video_client = VideoClient() video_client.SetTimeout(5.0) video_client.Init() # Start front camera code = video_client.StartLive(0) if code != 0: print(f"Failed to start camera: {code}") exit(1) # Subscribe to video frames sub = ChannelSubscriber("rt/video_frame", ImageFrame_) sub.Init() print("Video stream started. Press ESC to exit.") frame_count = 0 try: while True: frame = sub.Read(timeout=1.0) if frame: # Convert to numpy array img = np.frombuffer(frame.data, dtype=np.uint8) # Reshape if frame.encoding == "rgb8": img = img.reshape((frame.height, frame.width, 3)) img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) else: img = img.reshape((frame.height, frame.width)) img_bgr = img # Add frame counter cv2.putText(img_bgr, f"Frame: {frame_count}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # Display cv2.imshow("GO2 Front Camera", img_bgr) frame_count += 1 # Exit on ESC if cv2.waitKey(1) == 27: break else: print("No frame received") finally: # Cleanup cv2.destroyAllWindows() video_client.StopLive() print("Video stream stopped") ``` -------------------------------- ### Install CycloneDDS and Reinstall SDK Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/README.md This bash script provides instructions for installing CycloneDDS and setting the necessary environment variables. It is a solution for the 'Channel factory init error' troubleshooting step. After installation, the SDK needs to be reinstalled. ```bash # Install CycloneDDS git clone https://github.com/eclipse-cyclonedds/cyclonedds -b releases/0.10.x cd cyclonedds && mkdir build install && cd build cmake .. -DCMAKE_INSTALL_PREFIX=../install cmake --build . --target install # Set environment export CYCLONEDDS_HOME=~/cyclonedds/install export CMAKE_PREFIX_PATH=~/cyclonedds/install # Reinstall SDK pip3 install -e . ``` -------------------------------- ### Install Unitree SDK2 Python from Source Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Installs the Unitree SDK2 Python package from its source code. Ensure Python 3 and pip are installed. ```bash cd ~ sudo apt install python3-pip git clone https://github.com/unitreerobotics/unitree_sdk2_python.git cd unitree_sdk2_python pip3 install -e . ``` -------------------------------- ### Complete GO2 Obstacles Avoid Client Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-obstacles-avoid-client.md A comprehensive example demonstrating the full lifecycle of using the ObstaclesAvoidClient, including initialization, state checking, enabling/disabling avoidance, and commanding movement. ```python import sys import time from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.obstacles_avoid.obstacles_avoid_client import ObstaclesAvoidClient # Initialize if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create client client = ObstaclesAvoidClient() client.SetTimeout(5.0) client.Init() # Check current state code, enabled = client.SwitchGet() print(f"Obstacle avoidance: {'enabled' if enabled else 'disabled'}") # Enable obstacle avoidance client.SwitchSet(True) print("Obstacle avoidance enabled") # Move with avoidance active for i in range(10): client.Move(0.3, 0.0, 0.0) time.sleep(0.5) # Disable avoidance client.SwitchSet(False) print("Obstacle avoidance disabled") ``` -------------------------------- ### Complete PyGameJoystick Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/utils-joystick.md A comprehensive example showing joystick initialization, polling for 10 seconds, detecting button presses, analog input thresholds, and double-click detection. ```python import time from unitree_sdk2py.utils.joystick import PyGameJoystick # Initialize pygame joystick js = PyGameJoystick() print("Joystick initialized. Move sticks and press buttons...") for i in range(100): # Poll for 10 seconds at 10 Hz js.update() # Button presses if js.A.on_pressed: print("A button pressed") if js.start.on_pressed: print("Start pressed") # Analog inputs if abs(js.LX.data) > 0.5: print(f"Left stick X: {js.LX.data:.3f}") if abs(js.LY.data) > 0.5: print(f"Left stick Y: {js.LY.data:.3f}") # Double-click detection if js.X.click_count >= 2: print("X button double-clicked") js.X.reset_click_count() time.sleep(0.1) ``` -------------------------------- ### Complete G1 Loco Client Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/g1-loco-client.md A comprehensive example demonstrating the initialization of the LocoClient, setting communication parameters, transitioning to a ready state, controlling balance mode, executing movement commands (forward, rotate), and finally stopping and sitting. ```python import time import sys from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.g1.loco.g1_loco_client import LocoClient # Initialize communication if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create and initialize client client = LocoClient() client.SetTimeout(10.0) client.Init() # Transition to ready state client.Start() time.sleep(1.0) # Set balance mode client.SetBalanceMode(2) time.sleep(0.5) # Move forward client.SetVelocity(0.5, 0.0, 0.0, 2.0) time.sleep(2.0) # Rotate client.SetVelocity(0.0, 0.0, 0.5, 1.0) time.sleep(1.0) # Stop and sit client.StopMove() time.sleep(0.5) client.Sit() ``` -------------------------------- ### Set CYCLONEDDS_HOME and Install SDK Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Sets the CYCLONEDDS_HOME environment variable to the CycloneDDS installation path and then installs the Unitree SDK2 Python package. ```bash cd ~/unitree_sdk2_python export CYCLONEDDS_HOME=~/cyclonedds/install pip3 install -e . ``` -------------------------------- ### Install CycloneDDS Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Provides bash commands to clone, build, and install CycloneDDS from source. It also includes setting environment variables for CycloneDDS. ```bash # Install cyclonedds cd ~ git clone https://github.com/eclipse-cyclonedds/cyclonedds -b releases/0.10.x cd cyclonedds && mkdir build install && cd build cmake .. -DCMAKE_INSTALL_PREFIX=../install cmake --build . --target install # Set paths export CYCLONEDDS_HOME=~/cyclonedds/install export CMAKE_PREFIX_PATH=~/cyclonedds/install pip3 install -e . ``` -------------------------------- ### Set Arm Task Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/g1-loco-client.md Example demonstrating how to set the arm to a specific task using the SetTaskId function. ```python # Set arm to a specific task client.SetTaskId(1) ``` -------------------------------- ### Complete Sport Client Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Demonstrates initializing the SportClient, setting a timeout, initializing the client, and executing basic commands like StandUp, Move, StopMove, and StandDown. ```python import time import sys from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient # Initialize communication if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create and initialize sport client client = SportClient() client.SetTimeout(10.0) client.Init() # Execute commands client.StandUp() time.sleep(1.0) client.Move(0.3, 0.0, 0.0) # Move forward time.sleep(2.0) client.StopMove() time.sleep(0.5) client.StandDown() ``` -------------------------------- ### Multi-Camera Handling with Video Client Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Demonstrates how to initialize the VideoClient and start live streams from multiple cameras (front and side). It also shows how to subscribe to the respective video frame topics for each camera. ```python from unitree_sdk2py.go2.video.video_client import VideoClient from unitree_sdk2py.core.channel import ChannelSubscriber from unitree_sdk2py.idl.unitree_go.msg.dds_ import ImageFrame_ video_client = VideoClient() video_client.SetTimeout(5.0) video_client.Init() # Start both cameras video_client.StartLive(0) # Front video_client.StartLive(1) # Side # Subscribe to both topics if available front_sub = ChannelSubscriber("rt/video_frame_front", ImageFrame_) side_sub = ChannelSubscriber("rt/video_frame_side", ImageFrame_) front_sub.Init() side_sub.Init() # Process both streams while True: front_frame = front_sub.Read(timeout=0.5) side_frame = side_sub.Read(timeout=0.5) if front_frame: # Process front camera pass if side_frame: # Process side camera pass ``` -------------------------------- ### VideoClient Initialization and Usage Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Demonstrates how to initialize the VideoClient, set a timeout, start live streaming from the front camera, retrieve a video frame, and stop streaming. ```APIDOC ## VideoClient Manages video stream acquisition from robot cameras. ### `__init__` ```python def __init__(self): ``` **Example:** ```python from unitree_sdk2py.go2.video.video_client import VideoClient client = VideoClient() client.SetTimeout(5.0) client.Init() ``` ### `Init` Initialize video client and register camera APIs. ```python def Init(self): ``` **Return:** `None` ### `StartLive` Start live video streaming from a camera. ```python def StartLive(self, camera_id: int) -> int: ``` | Parameter | Type | Description | |-----------|------|-------------| | `camera_id` | `int` | Camera identifier (0=front, 1=side) | **Return:** `int` - Error code (0 on success). **Example:** ```python # Start front camera code = client.StartLive(0) if code == 0: print("Front camera streaming") # Start side camera code = client.StartLive(1) ``` ### `StopLive` Stop video streaming. ```python def StopLive(self) -> int: ``` **Return:** `int` - Error code (0 on success). **Example:** ```python client.StopLive() ``` ### `GetVideoFrame` Retrieve current video frame as raw bytes. ```python def GetVideoFrame(self) -> bytes: ``` **Return:** `bytes` - Raw frame data or None if no frame available. **Note:** Returns raw bytes; use OpenCV or similar to decode. ### `GetCameraCalibration` Get camera calibration parameters. ```python def GetCameraCalibration(self, camera_id: int) -> tuple[int, dict]: ``` | Parameter | Type | Description | |-----------|------|-------------| | `camera_id` | `int` | Camera identifier | **Return:** `tuple[code, calibration]` - `code` - `int`: 0 on success - `calibration` - `dict`: Calibration parameters (focal length, principal point, distortion) or None ``` -------------------------------- ### Basic PyGameJoystick Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/utils-joystick.md Demonstrates how to initialize PyGameJoystick, update its state in a loop, and check for button presses and analog stick movements. ```python import pygame from unitree_sdk2py.utils.joystick import PyGameJoystick pygame.init() pygame.joystick.init() js = PyGameJoystick() while True: js.update() if js.A.on_pressed: print("A pressed") if js.LX.data > 0.5: print("Moving right") ``` -------------------------------- ### PathPoint Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Example of creating a PathPoint object for a trajectory waypoint. ```python from unitree_sdk2py.go2.sport.sport_client import PathPoint # Create a waypoint point = PathPoint( timeFromStart=0.0, x=0.5, y=0.0, yaw=0.0, vx=0.2, vy=0.0, vyaw=0.0 ) ``` -------------------------------- ### ChannelPublisher Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/core-channel.md Demonstrates the complete lifecycle of a ChannelPublisher, including initialization, message publishing, and closing. Requires prior initialization of the channel factory. ```python from unitree_sdk2py.core.channel import ChannelPublisher, ChannelFactoryInitialize from unitree_sdk2py.idl.unitree_go.msg.dds_ import SportModeState_ ChannelFactoryInitialize(0, "eth0") pub = ChannelPublisher("rt/robot_state", SportModeState_) pub.Init() msg = SportModeState_() pub.Write(msg) pub.Close() ``` -------------------------------- ### Set Environment Variables for CycloneDDS Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Configure CycloneDDS by setting environment variables for installation paths and configuration URIs. This example shows how to export these variables before running a Python script. ```bash export CYCLONEDDS_HOME=~/cyclonedds/install export CMAKE_PREFIX_PATH=~/cyclonedds/install python3 sport_client.py enp2s0 ``` -------------------------------- ### PathPoint Initialization and Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/b2-sport-client.md Demonstrates how to initialize PathPoint objects with time, position, and velocity parameters, and then use them to command the robot's trajectory following. ```python from unitree_sdk2py.b2.sport.sport_client import PathPoint points = [ PathPoint(0.0, 0.0, 0.0, 0.0, 0.2, 0.0, 0.0), PathPoint(1.0, 0.2, 0.0, 0.0, 0.2, 0.0, 0.0), PathPoint(2.0, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0), ] client.TrajectoryFollow(points) ``` -------------------------------- ### High-Level Control Examples Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Demonstrates different high-level control actions for the robot. Uncomment the desired test method. ```python test.StandUpDown() # Stand up and lie down # test.VelocityMove() # Velocity control # test.BalanceAttitude() # Attitude control # test.TrajectoryFollow() # Trajectory tracking # test.SpecialMotions() # Special motions ``` -------------------------------- ### Low-Level Robot Control Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Executes a low-level control example for the robot, outputting joint and IMU data. Replace 'enp2s0' with your robot's network interface name. Ensure high-level motion services are off. ```bash python3 ./example/low_level/lowlevel_control.py enp2s0 ``` -------------------------------- ### Robot State Service Switch Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/errors.md Demonstrates how to switch robot services and handle specific error codes like service protection. ```python from unitree_sdk2py.go2.robot_state.robot_state_client import RobotStateClient from unitree_sdk2py.rpc.internal import RPC_OK client = RobotStateClient() client.SetTimeout(5.0) client.Init() code = client.ServiceSwitch("sport", True) if code == 0: print("Service switched successfully") elif code == 5202: print("Service is protected and cannot be disabled") else: print(f"Service switch failed: {code}") ``` -------------------------------- ### Joystick Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/utils-joystick.md Shows how to instantiate a Joystick object and access its button and axis attributes to read input states and values. ```python from unitree_sdk2py.utils.joystick import Joystick js = Joystick() # Check button states if js.A.on_pressed: print("A button pressed") if js.A.click_count >= 2: print("Double-click detected") # Read analog sticks forward = -js.LY.data # Negate for intuitive forward direction strafe = js.LX.data print(f"Movement: forward={forward:.2f}, strafe={strafe:.2f}") ``` -------------------------------- ### Compile and Install CycloneDDS Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Compiles and installs CycloneDDS, a dependency for the Unitree SDK2 Python. This is a prerequisite for resolving 'Could not locate cyclonedds' errors. ```bash cd ~ git clone https://github.com/eclipse-cyclonedds/cyclonedds -b releases/0.10.x cd cyclonedds && mkdir install && cd build cmake .. -DCMAKE_INSTALL_PREFIX=../install cmake --build . --target install ``` -------------------------------- ### ChannelSubscriber Usage Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/core-channel.md Demonstrates the basic usage of a ChannelSubscriber, including initialization, performing a blocking read, and closing the subscriber. Requires prior initialization of the channel factory. ```python from unitree_sdk2py.core.channel import ChannelSubscriber, ChannelFactoryInitialize from unitree_sdk2py.idl.unitree_go.msg.dds_ import SportModeState_ ChannelFactoryInitialize(0, "eth0") sub = ChannelSubscriber("rt/robot_state", SportModeState_) sub.Init() # Blocking read msg = sub.Read(timeout=2.0) if msg: print(f"Received: {msg}") sub.Close() ``` -------------------------------- ### Create Time_ Instance Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/types.md Example of creating an instance of the Time_ dataclass with specified seconds and nanoseconds. Used for setting timestamps. ```python from unitree_sdk2py.idl.builtin_interfaces.msg.dds_ import Time_ timestamp = Time_(sec=1234567890, nanosec=500000000) ``` -------------------------------- ### Create and Use a Periodic Timer Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/advanced-topics.md Shows how to create a periodic timer using `Timerfd` from the SDK. The timer can be started with a specified interval and waited upon. ```python from unitree_sdk2py.utils.timerfd import Timerfd # Create periodic timer timer = Timerfd() timer.start(0.1) # 100ms interval while True: timer.wait() print("Timer fired") ``` -------------------------------- ### Run DDS Publisher Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Starts the DDS publisher script for the Unitree SDK2 Python. This script sends data over DDS. ```bash python3 ./example/helloworld/publisher.py ``` -------------------------------- ### Create a Flask Web Interface for Robot Control Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/advanced-topics.md Demonstrates how to create a Flask web application to control the Unitree robot. It exposes endpoints for standing up, moving, and getting the robot's state. ```python from flask import Flask, jsonify, request from unitree_sdk2py.go2.sport.sport_client import SportClient app = Flask(__name__) robot = SportClient() robot.SetTimeout(10.0) robot.Init() @app.route('/stand', methods=['POST']) def stand_up(): code = robot.StandUp() return jsonify({"status": "success" if code == 0 else "failed", "code": code}) @app.route('/move', methods=['POST']) def move(): data = request.json vx = data.get('vx', 0.0) vy = data.get('vy', 0.0) vyaw = data.get('vyaw', 0.0) code = robot.Move(vx, vy, vyaw) return jsonify({"code": code}) @app.route('/state', methods=['GET']) def get_state(): # Would need to implement state monitoring return jsonify({"status": "running"}) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) ``` -------------------------------- ### Button Click Counting Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/utils-joystick.md Demonstrates how to track button presses, detect double-clicks, and reset the click counter using the Button class. ```python from unitree_sdk2py.utils.joystick import Joystick import time joystick = Joystick() joystick.A(1) # Press A button print(joystick.A.click_count) # 1 time.sleep(0.15) joystick.A(1) # Press again quickly print(joystick.A.click_count) # 2 (double-click) joystick.A.reset_click_count() print(joystick.A.click_count) # 0 ``` -------------------------------- ### Configure Client with Short Timeout Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Use a short timeout for quick checks or operations where immediate feedback is expected. This example sets the timeout to 1.0 second. ```python # Short timeout for quick checks quick_client = SportClient() quick_client.SetTimeout(1.0) ``` -------------------------------- ### Axis Deadzone and Smoothing Example Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/utils-joystick.md Illustrates configuring and using the Axis class for analog input, including setting a custom deadzone and smoothing factor. ```python from unitree_sdk2py.utils.joystick import Axis axis = Axis() axis.smooth = 0.05 # Slower smoothing axis.deadzone = 0.15 # Larger deadzone axis(0.03) # Below deadzone, output ~0 print(axis.data) # ~0 axis(0.9) # Large deflection print(axis.data) # Gradual approach to 0.9 ``` -------------------------------- ### Basic GO2 Robot Control Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/README.md Initialize DDS communication and control a GO2 robot using the SportClient. This example demonstrates standing up, moving forward, and standing down. ```python import sys import time from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient # Initialize DDS communication if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # Create and initialize sport client client = SportClient() client.SetTimeout(10.0) client.Init() # Execute commands client.StandUp() time.sleep(1.0) client.Move(0.5, 0.0, 0.0) # Move forward time.sleep(2.0) client.StopMove() client.StandDown() ``` -------------------------------- ### Create Channel with Custom DDS QoS Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Create a DDS channel with custom Quality of Service (QoS) policies. This example demonstrates setting reliability and history policies for a specific topic. ```python from cyclonedds.qos import Qos, Policy from unitree_sdk2py.core.channel import ChannelFactory factory = ChannelFactory() factory.Init(0, "eth0") # Create custom QoS qos = Qos( Policy.Reliability.BestEffort, Policy.History.KeepLast(10) ) # Create channel with custom QoS channel = factory.CreateChannel("rt/custom_topic", SomeType, qos) ``` -------------------------------- ### Subscribe to Robot State Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/types.md Example of subscribing to the robot state topic using SportModeState_. Initializes the channel factory and sets up a subscriber to read state information. ```python from unitree_sdk2py.core.channel import ChannelSubscriber, ChannelFactoryInitialize from unitree_sdk2py.idl.unitree_go.msg.dds_ import SportModeState_ ChannelFactoryInitialize(0, "eth0") sub = ChannelSubscriber("rt/robot_state", SportModeState_) sub.Init() state = sub.Read(timeout=1.0) if state: print(f"Position: ({state.position[0]:.2f}, {state.position[1]:.2f})") print(f"Velocity: {state.velocity[0]:.2f} m/s") ``` -------------------------------- ### Start Live Video Streaming Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Initiates live video streaming from either the front (ID 0) or side (ID 1) camera. Checks the return code to confirm successful streaming. ```python # Start front camera code = client.StartLive(0) if code == 0: print("Front camera streaming") # Start side camera code = client.StartLive(1) ``` -------------------------------- ### Integrate Unitree SDK with ROS2 Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/advanced-topics.md Provides an example of integrating the Unitree SDK with ROS2. It creates a ROS2 node that subscribes to `cmd_vel` messages and controls the robot's movement. ```python import rclpy from rclpy.node import Node from geometry_msgs.msg import Twist from unitree_sdk2py.go2.sport.sport_client import SportClient class UnitreeNode(Node): def __init__(self): super().__init__('unitree_driver') self.robot = SportClient() self.robot.SetTimeout(10.0) self.robot.Init() self.subscription = self.create_subscription( Twist, 'cmd_vel', self.cmd_vel_callback, 10 ) def cmd_vel_callback(self, msg): vx = msg.linear.x vy = msg.linear.y vyaw = msg.angular.z self.robot.Move(vx, vy, vyaw) # Usage rclpy.init() node = UnitreeNode() rclpy.spin(node) ``` -------------------------------- ### Configure Client with Long Timeout Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Use a longer timeout for motion commands or operations that may take more time to complete. This example sets the timeout to 10.0 seconds. ```python # Long timeout for motion commands motion_client = SportClient() motion_client.SetTimeout(10.0) ``` -------------------------------- ### Run a Worker Function in a Background Thread Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/advanced-topics.md Demonstrates how to start and manage a background thread for a worker function using Python's `Thread` class. The thread is set as a daemon thread. ```python from threading import Thread def worker(): print("Running in background thread") thread = Thread(target=worker, daemon=True) thread.start() thread.join() ``` -------------------------------- ### Handling Channel Factory Initialization Failure Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/errors.md Catches and prints errors during the initialization of the channel factory, often due to an invalid interface name or CycloneDDS setup issues. Use this to diagnose and resolve channel initialization problems. ```python from unitree_sdk2py.core.channel import ChannelFactoryInitialize try: ChannelFactoryInitialize(0, "invalid_interface") except Exception as e: print(f"Channel factory init error: {e}") # Check: Interface name, CycloneDDS installation, permissions ``` -------------------------------- ### Initialize and Configure VideoClient Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Instantiate the VideoClient, set a timeout, and initialize the client for use. This is the first step before calling other video-related methods. ```python from unitree_sdk2py.go2.video.video_client import VideoClient client = VideoClient() client.SetTimeout(5.0) client.Init() ``` -------------------------------- ### Typical Initialization Sequence for GO2 Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Demonstrates the standard sequence for initializing DDS communication, creating service clients for robot state and sport control, querying initial state, and performing operations like standing up. ```python import sys from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient from unitree_sdk2py.go2.robot_state.robot_state_client import RobotStateClient # 1. Initialize DDS communication if len(sys.argv) > 1: ChannelFactoryInitialize(0, sys.argv[1]) else: ChannelFactoryInitialize(0) # 2. Create service clients state_client = RobotStateClient() state_client.SetTimeout(5.0) state_client.Init() sport_client = SportClient(enableLease=False) sport_client.SetTimeout(10.0) sport_client.Init() # 3. Query initial state code, services = state_client.ServiceList() if code == 0: print("Services available") # 4. Perform operations sport_client.StandUp() # 5. Cleanup (optional for short-lived scripts) ``` -------------------------------- ### Initialize RPC Client Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/rpc-client.md Instantiate an RPC client. Use `enableLease=True` for exclusive access to robot services. ```python from unitree_sdk2py.rpc.client import Client # Basic client without lease client = Client("sport", enableLease=False) # Client with lease (for exclusive access) client = Client("sport", enableLease=True) ``` -------------------------------- ### Initialize ObstaclesAvoidClient Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-obstacles-avoid-client.md Instantiate and configure the ObstaclesAvoidClient. Set a timeout and initialize the client to begin communication. ```python from unitree_sdk2py.go2.obstacles_avoid.obstacles_avoid_client import ObstaclesAvoidClient client = ObstaclesAvoidClient() client.SetTimeout(5.0) client.Init() ``` -------------------------------- ### Handstand Motion Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Controls the handstand motion. Use `enable=True` to start and `enable=False` to end. Returns an integer error code. ```python def HandStand(self, enable: bool) -> int: pass ``` -------------------------------- ### HandStand Function Signature Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/b2-sport-client.md Defines the function signature for controlling the handstand motion. Use 'enable' to start or end the handstand. ```python def HandStand(self, enable: bool) -> int: ``` -------------------------------- ### Init Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Initializes the client and registers all sport mode APIs. This must be called before any sport commands are issued. ```APIDOC ## `Init` ### Description Initializes the client and registers all sport mode APIs. This method must be called before any sport commands. ### Method `Init(self)` ### Return `None` ### Example ```python client.Init() ``` ``` -------------------------------- ### Get Server API Version Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/rpc-client.md Query the connected robot service to retrieve its API version. This is useful for compatibility checks. ```python code, version = client.GetServerApiVersion() if code == 0: print(f"Server API version: {version}") ``` -------------------------------- ### Adjust Message Frequency Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/README.md Use SetReportFreq() to adjust the state message frequency. This example sets the interval to 50ms for 5 seconds. ```python client.SetReportFreq(50, 5) # 50ms interval for 5 seconds ``` -------------------------------- ### Initialize Channel and Create SportClient Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/README.md This snippet demonstrates the initialization pattern for the Unitree SDK2 Python library. It shows how to initialize the communication channel and create a SportClient instance. Ensure ChannelFactoryInitialize is called once per application. ```python from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient # 1. Initialize channel (once per application) ChannelFactoryInitialize(0, "eth0") # 2. Create and configure client client = SportClient() client.SetTimeout(10.0) # 3. Initialize client (registers APIs) client.Init() # 4. Use client client.StandUp() ``` -------------------------------- ### ChannelPublisher Init Method Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/core-channel.md Enables the publisher, preparing it to send messages. This method should be called after initializing the ChannelPublisher. ```python def Init(self): ``` -------------------------------- ### Free Jump Motion Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Controls the free jump motion. Use `enable=True` to start and `enable=False` to stop. Returns an integer error code. ```python def FreeJump(self, enable: bool) -> int: pass ``` -------------------------------- ### Free Bound Motion Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Controls the free bound motion. Use `enable=True` to start and `enable=False` to stop. Returns an integer error code. ```python def FreeBound(self, enable: bool) -> int: pass ``` -------------------------------- ### Run DDS Subscriber Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Starts the DDS subscriber script for the Unitree SDK2 Python. This script receives data published via DDS. ```bash python3 ./example/helloworld/subscriber.py ``` -------------------------------- ### Init Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-obstacles-avoid-client.md Initializes and registers the obstacle avoidance APIs. This method must be called after client instantiation. ```APIDOC ### `Init` Initialize and register obstacle avoidance APIs. ```python def Init(self): ``` **Return:** `None` ``` -------------------------------- ### Perform Non-Blocking Move Operation Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/README.md Methods like Move() return immediately without waiting for confirmation. This example sends a non-blocking move command. ```python code = client.Move(0.5, 0.0, 0.0) # Non-blocking # Command sent; robot will execute ``` -------------------------------- ### Init Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/b2-sport-client.md Registers all sport mode APIs for the SportClient. ```APIDOC ## Init ### Description Register all sport mode APIs. ### Method `Init(self)` ### Return `None` ``` -------------------------------- ### Initialize Sport Client Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/INDEX.md Initializes the channel factory and the SportClient. Ensure you specify the correct network interface or use command-line arguments for dynamic selection. Set a timeout for client operations. ```python from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient ChannelFactoryInitialize(0, "eth0") # or sys.argv[1] client = SportClient() client.SetTimeout(10.0) client.Init() ``` -------------------------------- ### Initialize LocoClient Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/g1-loco-client.md Instantiate and initialize the LocoClient. Ensure to call SetTimeout and Init before issuing commands. ```python from unitree_sdk2py.g1.loco.g1_loco_client import LocoClient client = LocoClient() client.SetTimeout(10.0) client.Init() ``` -------------------------------- ### Move with Velocity and Duration Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/g1-loco-client.md Commands the robot to move with specified forward, lateral, and rotational velocities for a given duration. Includes examples for moving, rotating, and stopping. ```python # Move forward at 0.5 m/s client.SetVelocity(0.5, 0.0, 0.0, 1.0) # Move sideways with rotation client.SetVelocity(0.0, 0.3, 0.2, 2.0) # Stop client.SetVelocity(0.0, 0.0, 0.0, 0.5) ``` -------------------------------- ### Initialize Sport Client Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/b2-sport-client.md Initializes the SportClient and sets a timeout. Ensure to call Init() after creating the client. ```python from unitree_sdk2py.b2.sport.sport_client import SportClient client = SportClient() client.SetTimeout(10.0) client.Init() ``` -------------------------------- ### Initialize GO2 Sport and Robot State Clients Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/configuration.md Initialize the SportClient for controlling robot actions and the RobotStateClient for retrieving robot status information on GO2 models. Custom timeouts can be set for each client. ```python from unitree_sdk2py.go2.sport.sport_client import SportClient from unitree_sdk2py.go2.robot_state.robot_state_client import RobotStateClient # Sport service sport = SportClient() sport.SetTimeout(10.0) sport.Init() # Robot state service state = RobotStateClient() state.SetTimeout(5.0) state.Init() ``` -------------------------------- ### Execute Core Robot Commands Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/INDEX.md Demonstrates how to send core commands to the robot, such as standing up, moving, stopping movement, and dampening. Note that Move is non-blocking. ```python code = client.StandUp() # Return: 0 (success) or error code client.Move(vx, vy, vyaw) # Non-blocking velocity command code = client.StopMove() code = client.Damp() ``` -------------------------------- ### Create and Use ServiceState Object Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-robot-state-client.md Demonstrates how to create a ServiceState object and access its attributes to check service status. ```python state = ServiceState(name="sport", status=1, protect=False) print(f"Service {state.name} is {'on' if state.status == 1 else 'off'}") ``` -------------------------------- ### SportClient Initialization Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-sport-client.md Initializes the SportClient. Must be called before any other sport commands. Optionally enables lease-based exclusive access. ```APIDOC ## `__init__` ### Description Initializes the SportClient with optional lease-based exclusive access. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```python def __init__(self, enableLease: bool = False): ``` ### Parameters - **enableLease** (bool) - Optional - Enable lease-based exclusive access. Defaults to `False`. ### Example ```python from unitree_sdk2py.go2.sport.sport_client import SportClient client = SportClient() client.SetTimeout(10.0) client.Init() ``` ``` -------------------------------- ### Control Light and Volume Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/README.md Execute this script to cycle the robot's volume and light brightness. Replace 'enp2s0' with the correct network interface name for your robot. ```bash python3 ./example/vui_client/vui_client_example.py enp2s0 ``` -------------------------------- ### Map Error Codes to Names Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/errors.md This dictionary maps integer error codes to their corresponding string representations. Use the `describe_error` function to get a human-readable description for any given error code. ```python ERROR_CODES = { 0: "RPC_OK", 3001: "RPC_ERR_UNKNOWN", 3102: "RPC_ERR_CLIENT_SEND", 3103: "RPC_ERR_CLIENT_API_NOT_REG", 3104: "RPC_ERR_CLIENT_API_TIMEOUT", 3105: "RPC_ERR_CLIENT_API_NOT_MATCH", 3106: "RPC_ERR_CLIENT_API_DATA", 3107: "RPC_ERR_CLIENT_LEASE_INVALID", 3201: "RPC_ERR_SERVER_SEND", 3202: "RPC_ERR_SERVER_INTERNAL", 3203: "RPC_ERR_SERVER_API_NOT_IMPL", 3204: "RPC_ERR_SERVER_API_PARAMETER", 3205: "RPC_ERR_SERVER_LEASE_DENIED", 3206: "RPC_ERR_SERVER_LEASE_NOT_EXIST", 3207: "RPC_ERR_SERVER_LEASE_EXIST", 5201: "ROBOT_STATE_ERR_SERVICE_SWITCH", 5202: "ROBOT_STATE_ERR_SERVICE_PROTECTED", 4101: "SPORT_ERR_CLIENT_POINT_PATH", 4201: "SPORT_ERR_SERVER_OVERTIME", 4202: "SPORT_ERR_SERVER_NOT_INIT", } def describe_error(code): """Get human-readable error description.""" return ERROR_CODES.get(code, f"Unknown error {code}") ``` -------------------------------- ### Reduce Robot Video Frame Rate Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Configures the RobotStateClient to request video frames from the robot at a reduced frequency. This example sets the interval to 200ms (5 Hz) for a duration of 10 seconds. ```python from unitree_sdk2py.go2.robot_state.robot_state_client import RobotStateClient state = RobotStateClient() state.SetTimeout(5.0) state.Init() # Request video at 5 Hz instead of 10 Hz state.SetReportFreq(200, 10) # 200ms interval, 10 second duration ``` -------------------------------- ### Initialization Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/INDEX.md Initializes the communication channel and the SportClient for robot interaction. It's recommended to set a timeout for client operations. ```APIDOC ## Initialization ### Description Initializes the communication channel and the SportClient for robot interaction. It's recommended to set a timeout for client operations. ### Code ```python from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient ChannelFactoryInitialize(0, "eth0") # or sys.argv[1] client = SportClient() client.SetTimeout(10.0) client.Init() ``` ``` -------------------------------- ### Integrate Obstacle Avoidance with Sport Service Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-obstacles-avoid-client.md Demonstrates how to use the ObstaclesAvoidClient in conjunction with the SportClient for combined control, enabling autonomous movement while maintaining basic robot functions like standing up. ```python import sys from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.go2.sport.sport_client import SportClient from unitree_sdk2py.go2.obstacles_avoid.obstacles_avoid_client import ObstaclesAvoidClient ChannelFactoryInitialize(0, sys.argv[1]) # Sport service for basic commands sport = SportClient() sport.SetTimeout(10.0) sport.Init() # Obstacle avoidance for autonomous movement avoid = ObstaclesAvoidClient() avoid.SetTimeout(5.0) avoid.Init() # Stand up sport.StandUp() # Enable avoidance and move avoid.SwitchSet(True) avoid.Move(0.5, 0.0, 0.0) ``` -------------------------------- ### ChannelSubscriber Init Method Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/core-channel.md Enables the subscriber, preparing it to receive messages. It can optionally accept a handler for message reception and a queue length. ```python def Init(self, handler: Callable = None, queueLen: int = 0): ``` -------------------------------- ### Get Camera Calibration Parameters Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-video-client.md Retrieves calibration parameters for a specified camera. Returns an integer status code and a dictionary containing calibration details like focal length and distortion coefficients. ```python code, calibration = client.GetCameraCalibration(camera_id=0) ``` -------------------------------- ### Init Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/go2-robot-state-client.md Initializes and registers all robot state APIs. This method must be called before making any requests. ```APIDOC ### `Init` Initialize and register all robot state APIs. ```python def Init(self): ``` **Return:** `None` **Must be called before making any requests.** ``` -------------------------------- ### PathPoint Class Definition Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/types.md Represents a waypoint for trajectory planning, including time from start, position (x, y), yaw angle, and corresponding velocities. Supports up to 30 points and requires monotonically increasing time values. ```python from unitree_sdk2py.go2.sport.sport_client import PathPoint class PathPoint: def __init__(self, timeFromStart: float, x: float, y: float, yaw: float, vx: float, vy: float, vyaw: float): self.timeFromStart = timeFromStart # Seconds from start self.x = x # Position X (m) self.y = y # Position Y (m) self.yaw = yaw # Yaw angle (rad) self.vx = vx # Velocity X (m/s) self.vy = vy # Velocity Y (m/s) self.vyaw = vyaw # Yaw velocity (rad/s) ``` -------------------------------- ### LocoClient Initialization Source: https://github.com/unitreerobotics/unitree_sdk2_python/blob/master/_autodocs/api-reference/g1-loco-client.md Initializes the locomotion control client and sets a timeout. Must be called before any other commands. ```APIDOC ## LocoClient Main locomotion control client for G1. ### `__init__` ```python def __init__(self): ``` ### `Init` Register all locomotion APIs. ```python def Init(self): ``` **Return:** `None` **Must be called before any commands.** ### `SetTimeout` Sets the timeout for communication with the robot. ```python def SetTimeout(self, timeout: float): ``` | Parameter | Type | Description | |-----------|------|-------------| | `timeout` | `float` | Communication timeout in seconds | **Example:** ```python from unitree_sdk2py.g1.loco.g1_loco_client import LocoClient client = LocoClient() client.SetTimeout(10.0) client.Init() ``` ```