Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

python - Raspberry PI wifi signal transmission via UDP or TCPIP is inconsistent

I have an application where I am sending a on/off signal from one raspberry pi (Pi zero) via TCP/IP (or UDP) over wifi to another Raspberry pi (PI4). I need this transmission to be lag free as much as possible. I have tried using tcp/ip and the UDP protocols but in both cases I see inconsistent delays in receipt of data. The wifi is being generated locally with a dedicated wifi router and only two devices on the network are the Pis. Here is the section of the code on the Pi zero that sends the signal:

s=socket.socket()
port=12397
s.bind(('',port))
s.listen(5)
i=0
while runserver:
    try:
        c,addr = s.accept()
        print("Client connected")
        while True:
            if i==1:
                i=0
            else:
                i=1
            c.send(str(i))
            time.sleep(1) #Sleep for 1 second
        c.close()
    except:
        print("Client disconnected")

Here is the code that is running on the Pi 4 that receives the signal:

host = '192.168.43.2'
port = 12397
runclient = 1
while runclient:
    try:
        s = socket.socket()
        #This is to ensure that if the server disconnects for any reason
        #the signal being sent out is reset to 2 (unknown)
        s.settimeout(5.0)
        s.connect((host,port))
        try:
            while True:
                try:
                    flag.value = int(s.recv(1))
                except socket.timeout:
                    flag.value = int(2)
                    print("Server disconnected")
                    break
        except KeyboardInterrupt:
            s.shutdown(socket.SHUT_RDWR)
            s.close()
        #except socket.error as e:
        #    print(e.args[0])
        #    continue
    except:
        print("No Server", end='
')
        flag.value = int(2)

As you can see from the Pi Zero code, I am flipping the values between 1 and 0 every 1 second. What I expect to see on the Pi4 side is the received values following the same trend every 1 second. But what I end up seeing is that the time gap between signal changes vary between 0.2 to 1.5 and some times 2.5 seconds. I have tried to bring the router as close as possible to both the Pis (Both the Pis are within 4 feet of each other).

Does anyone have any ideas on why there is this delay in the receiving side? Is it the wifi buffering? What can be done to improve this situation?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...