RTDE SampleScript

I tried RTDE program. But It’s not go well. I attached my script, and error message, Please tell me , how to correct this script.

import socket
import struct
import select

UR Robot RTDE Configuration

ROBOT_IP = “192.168.1.56” # Change this to your robot’s IP
PORT = 30004 # Default RTDE port
DEFAULT_TIMEOUT = 2.0 # Increased timeout for stability

RTDE Packet IDs

RTDE_REQUEST_PROTOCOL_VERSION = 86
RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS = 79
RTDE_CONTROL_PACKAGE_START = 83

def connect_rtde(ip, port):
“”“Connects to the UR robot’s RTDE server.”“”
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(DEFAULT_TIMEOUT)

try:
    sock.connect((ip, port))
    print(f"✅ Connected to RTDE server at {ip}:{port}")
    return sock
except socket.error as e:
    print(f"❌ Connection failed: {e}")
    return None

def send_command(sock, cmd, payload=b"“):
“”“Sends a command to the RTDE server.””"
size = struct.calcsize(“>HB”) + len(payload)
buf = struct.pack(“>HB”, size, cmd) + payload

try:
    sock.sendall(buf)
    print(f"📤 Sent command: {cmd}")
    return True
except socket.error as e:
    print(f"❌ Send failed: {e}")
    return False

def receive_data(sock):
“”“Receives an RTDE packet, extracts header and payload.”“”
try:
# Wait for data with a timeout
ready = select.select([sock], , , DEFAULT_TIMEOUT)
if not ready[0]:
print(“:warning: No data received within timeout”)
return None, None

    # Receive the 3-byte header
    header = sock.recv(3)
    if len(header) < 3:
        print("⚠️ Incomplete header received")
        return None, None

    # Extract packet size and command ID
    packet_size, cmd = struct.unpack(">HB", header)

    # Receive the payload
    payload = b""
    while len(payload) < packet_size - 3:
        chunk = sock.recv(packet_size - 3 - len(payload))
        if not chunk:
            print("⚠️ Connection closed unexpectedly")
            return None, None
        payload += chunk

    print(f"📥 Received packet: cmd={cmd}, size={packet_size}, payload={len(payload)} bytes")
    return cmd, payload
except socket.timeout:
    print("❌ Receive timeout")
    return None, None
except socket.error as e:
    print(f"❌ Receive failed: {e}")
    return None, None

def test_rtde():
“”“Test RTDE communication with the UR robot.”“”
sock = connect_rtde(ROBOT_IP, PORT)
if not sock:
return

try:
    # **1. Protocol Version Negotiation**
    version_payload = struct.pack(">H", 2)  # RTDE Protocol Version 2
    if send_command(sock, RTDE_REQUEST_PROTOCOL_VERSION, version_payload):
        cmd, response = receive_data(sock)
        print(f"🔗 Protocol Version Response: cmd={cmd}, response={response}")

    # **2. Setup Outputs (actual_TCP_pose)**
    output_payload = "actual_TCP_pose,double\0".encode("ascii")  # Proper null-terminated string
    if send_command(sock, RTDE_CONTROL_PACKAGE_SETUP_OUTPUTS, output_payload):
        cmd, response = receive_data(sock)
        print(f"📝 Output Setup Response: cmd={cmd}, response={response}")

    # **3. Start Receiving Data**
    if send_command(sock, RTDE_CONTROL_PACKAGE_START):
        cmd, response = receive_data(sock)
        print(f"🚀 Start Response: cmd={cmd}, response={response}")

    # **4. Receive and Process Data**
    for _ in range(5):  # Fetch data 5 times
        cmd, data = receive_data(sock)
        if data and len(data) >= 48:
            try:
                pose = struct.unpack(">dddddd", data[:48])  # Extract TCP Pose (X, Y, Z, RX, RY, RZ)
                print(f"🤖 Robot Pose: {pose}")
            except struct.error as e:
                print(f"⚠️ Unpack error: {e}")
        else:
            print(f"⚠️ Unexpected data length: {len(data) if data else 'None'}")
finally:
    if sock:
        print("🔌 Disconnecting from RTDE server...")
        sock.close()

if name == “main”:
test_rtde()

////////////////////////////////////////////////////////////////////////////////////////////////////
Terminal error message
PS C:\MyApps\URScript\RTDE_TRIAL_A> & C:/Users/prosu/miniconda3/envs/bristol_otg/python.exe c:/MyApps/URScript/RTDE_TRIAL_A/Just_Pose_Receive.py
:white_check_mark: Connected to RTDE server at 192.168.1.56:30004
:outbox_tray: Sent command: 86
:inbox_tray: Received packet: cmd=86, size=4, payload=1 bytes
:link: Protocol Version Response: cmd=86, response=b’\x01’
:outbox_tray: Sent command: 79
:inbox_tray: Received packet: cmd=79, size=23, payload=20 bytes
:memo: Output Setup Response: cmd=79, response=b’\x01NOT_FOUND,NOT_FOUND’
:outbox_tray: Sent command: 83
:inbox_tray: Received packet: cmd=83, size=4, payload=1 bytes
:rocket: Start Response: cmd=83, response=b’\x00’
:warning: No data received within timeout