- A unity program that runs a simulation of a robot
- A unity plugin that runs a small tcp server. It stores some values such as 'motor speed', 'sensor value', 'servo position'.
- A python script that connects to the server to set values that unity reads for controlling the robot, or to retrieve values that unity stores from the 'sensors'.
My simulated robot now has 2 motors, 2 neck servos, 2 eye servos, front, back, left, right and bottom range finders and a couple of eye cameras.
The server code is a bit of bog standard c++ use of sockets. It reads in a 4 byte message length followed by a text based command, interprets it and sends a response. The code is longer than I'd like in true c++ style, but the nice python interpreter is much more precise:
import socket
import struct
print("Running inputtest.py")
HOST = 'localhost' # The remote host
PORT = 5152 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
#handy recvall function to block until a fixed number of bytes are read
def recvall(sock,requested_bytes):
total_data=bytes(0)
while len(total_data) < requested_bytes:
data = sock.recv(requested_bytes-len(total_data))
total_data = total_data + data
return total_data
#Recv a block of text as a msg with 4 byte length header
def RecvText():
lenbytes = struct.unpack("<i",recvall(s,4))[0]
data = recvall(s,lenbytes);
return data.decode()
print("Begin client loop")
while True:
#read in a message to send
val = input("Please input something\n")
if(val == "q"): #bail out if quit requested
break;
#get the number of bytes
lenbytes = struct.pack("<i",len(val))
#send the bytes and print out the response
s.sendall(lenbytes)
s.sendall(val.encode())
print(RecvText())
s.close();
Using this little script I can send commands such as:
set motor0 0.5
This results in:
set motor0 0.5
This results in:
- The script posting the text "set motor0 0.5" to the server
- The servo decoding this and assigning 0.5 to the variable RequestedMotorPower[0]
- Unity querying the latest requested power for motor0 and assigning it to the motor joint in the simulation
Its the sort of thing that's much better described in video though, so here's a little demo:
Next up I'll getting those camera feeds through to python somehow, and get a slightly prettier python project going on with some proper modules to make the whole thing a bit more readable. In theory from there I should be able to run the very same scripts on the raspberry pi and have it controlling the simulation.











