Hi everyone,
In one of my current projects, I connect multiple esp32 (programmed with arduino code) to a python server on my local network. For the wifi connection and the socket creation, I use the WiFi.h library. The connection is fine, and I can send/receive packets without transmission problems.
Problems start when I try to have low latency packet sending (~1ms would be perfect). When my server send data to the esps, messages arrived grouped and not just after the sending. The problem looks like a buffer problem, but even with the proper flags set, the delay persists.
Here is a simplified version of my codes to exactly understand what I am doing
ESP code
#include <Arduino.h>
#include <WiFi.h>
void setup() {
Serial.begin(115200);
delay(500);
// Connect to wifi
config_t config = configs[0];
WiFi.begin(myssid, mypassword);
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println("\nconnected");
// Connect to serveur
IPAddress remoteHost(192, 168, 1, 101);
WiFiClient socket;
socket.setNoDelay(true);
Serial.printf("Connecting to server %s:%d\n", remoteHost, 4040);
while (!socket.connect(remoteHost, 4040)) {
Serial.print('.');
delay(1000);
}
Serial.printf("\nConnected !\n");
// Get a bunch of messages
while (socket.connected()) {
while (socket.available() > 0) {
uint8_t c;
socket.read(&c, 1);
socket.flush();
Serial.printf("%d\treceived at %d\n", c, millis());
}
}
}
Python server code:
import socket
import time;
if __name__ == "__main__":
with socket.create_server(("", 4040)) as socket_server:
print("server created")
socket_server.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
s, address = socket_server.accept()
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
print("client connected")
for i in range(10):
s.sendall(i.to_bytes(length=1, byteorder='big', signed=False))
print(time.time())
time.sleep(.1)
The outputs of the python correspond to a message send every 100ms:
server created
client connected
1690365932.8049686
1690365932.9055307
1690365933.0061347
1690365933.1067114
1690365933.207289
1690365933.307892
1690365933.4085824
1690365933.5089648
1690365933.6095665
1690365933.710132
The output of the esp32:
.
connected
Connecting to server
Connected !
0 received at 5694
1 received at 5921
3 received at 6048
4 received at 6099
5 received at 6419
8 received at 6541
9 received at 6668
As you can see in the python output, the messages are send every 100ms with a 1ms variability while the esp is receiving with chaotic delays.
I did another experiment by implementing a python client instead of the esp. I ran the code on a different machine than the server. The python client receives the packets with a 100ms delay (as expected) with 1ms variability. So, the problem is definitely on the ESP + WiFi.h side.
Do you have any idea on what is happening and how to solve the issue ?