# RTDE SampleScript

**URL:** <https://forum.universal-robots.com/t/rtde-samplescript/38526>\
**Category:** Technical Questions\
**Created:** [February 12, 2025, 1:30pm UTC](https://forum.universal-robots.com/t/rtde-samplescript/38526 "2025-02-12T13:30:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![hideto.kato](https://avatars.discourse-cdn.com/v4/letter/h/5f8ce5/32.png) [@hideto.kato](https://forum.universal-robots.com/u/hideto.kato)\
**Post date:** [February 12, 2025, 1:30pm UTC](https://forum.universal-robots.com/t/rtde-samplescript/38526/1 "2025-02-12T13:30:54Z")

</div>

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(“⚠ 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  
✅ Connected to RTDE server at 192.168.1.56:30004  
📤 Sent command: 86  
📥 Received packet: cmd=86, size=4, payload=1 bytes  
🔗 Protocol Version Response: cmd=86, response=b’\x01’  
📤 Sent command: 79  
📥 Received packet: cmd=79, size=23, payload=20 bytes  
📝 Output Setup Response: cmd=79, response=b’\x01NOT\_FOUND,NOT\_FOUND’  
📤 Sent command: 83  
📥 Received packet: cmd=83, size=4, payload=1 bytes  
🚀 Start Response: cmd=83, response=b’\x00’  
⚠ No data received within timeout
