I try to connect some external hardware to Blender via tcp. I could connect to it and it gives back the values I request.
Now I want to repeat this request every second, or even more often, to kind of stream the values. Here is what I did until now:
import socket import struct # values ip = "192.168.1.11" port = 51955 command = "S01" cs = "80" # create socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind socket s.connect((ip,port)) # pack data data = struct.pack("bsssssb",0x01,command,command,command,cs,cs,0x17) # send command s.send(data) # get answer ack = s.recv(1024) speed = s.recv(1024) # close socket s.close() print "speed: ",float(speed[4:len(speed)-3])*3.6,"km/h"
After sending the command to the hardware, I get 2 packets: the first one (“ack”) got only a ACK flag, the second (“speed”) the value I want.
Right now, the script runs with an “Always”-sensor (pulse OFF) only once. And it’s all fine. But how can I get this to “stream” the values, meaning repeating the request more often?
When I activate pulsing on the Always sensor, the packets on the network seem to mess up somehow, only one packet arrives and the script stops, waiting for the second.
Is there a way to connect the socket “global”, keep it open, and only send the command and recieve the result each frame, instead of doing the whole process (open -> send -> recieve -> close) each frame?
I thought about something like threading maybe, but could not get anything working.
Would be great if someone could give me a hint, how to handle such a tcp connection best.
if it’s of note: this is what happens on the network when I run the script:
packet 6 is the send() command, packet 8 is the first ACK and packet 9 is the answer containing the value