Universal Robots Forum

Sending commands with Python

I am trying to send script commands with Python, and got some of it working

import socket
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(('192.168.1.99', 30002))

def sendCommand(cmd):
    #cmd = 'def program():\n ' + cmd + '\n end\n'
    cmd = cmd + '\n'
    s.sendall(cmd.encode())

while (1):
    sendCommand('set_digital_out(0, False)')
    time.sleep(1)
    sendCommand('set_digital_out(0, True)')
    time.sleep(1)

As this it works, and turns the digital out 0 on and off. But if I try to wrap it in program() instead, nothing happens. Am I sending it wrong? Or does it expect to receive the function different?

I know I don’t need to put it like that for just a single command, but it is in preperation for something more exciting. :slight_smile:

Why is it I always find the problem right after posting here???

The problem was the space in β€œ\n end\n”

import socket
import time

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
s.connect(('192.168.1.99', 30002))

def sendCommand(cmd):
    cmd = 'def program():\n ' + cmd + '\nend\n'
    print(cmd)
    s.sendall(cmd.encode())

while (1):
    sendCommand('set_digital_out(0, False)')
    time.sleep(1)
    sendCommand('set_digital_out(0, True)')
    time.sleep(1)

This works, and will just toggle digital out 0 on and off.

2 Likes