Using UDP to control robot via python

1.1k views Asked by At

I'm working on a robot using a raspberrypi. I was looking for a library that could help me with the networking stuff, like packets &co. So i'm using this code to select the commands I receive:

def selectPacket(x):
    if x == '00': 
        return '00'
    elif x == "01":
        Date = datetime.now()
        return str(Date.microsecond)
    elif x == "02":
        return '98'
    elif x == "03":
        return '98'
    elif x == "04":
        return '98'
    elif x == "05":
        return '98'
    else: 
        return '99'

I'm sure that there is a lib to make quick servers and clients using python, I want to use UDP because the connection I will use will be very unstable, so tcp is out of question.

1

There are 1 answers

1
Hexoul On

Because controlling robot depends on complex parts such as how many legs they have, how many joints they have and so on, I think there is no library you want. And connection phase on python is too simple to make a library.

Here are simple UDP Client/Server code:

UDP Server

import socket, traceback
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind(('', 5000))

print "Listening for broadcasts..."

while 1:
    try:
        message, address = s.recvfrom(8192)
        print "Got message from %s: %s" % (address, message)
        s.sendto("Hello from server", address)
        print "Listening for broadcasts..."
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        traceback.print_exc()

UDP Client

import socket, sys
dest = ('<broadcast>', 5000)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto("Hello from client", dest)
print "Listening for replies."

while 1:
    (buf, address) = s.recvfrom(2048)
    if not len(buf):
        break
    print "Received from %s: %s" % (address, buf)
    s.sendto("echo", dest)

Also, if you have complex logic and need to separate into multiple parts that can be communication, control or I/O, refer Event-driven programming: http://etutorials.org/Programming/Python+tutorial/Part+IV+Network+and+Web+Programming/Chapter+19.+Sockets+and+Server-Side+Network+Protocol+Modules/19.3+Event-Driven+Socket+Programs/)