All code can be found on my GitHub. Measuring latency requires knowing the time a signal is sent and the time a signal is received. As the ESP32 and my laptop running the python server don’t share a clock, this isn’t easy. The proper thing to do would be to somehow hook both systems up to the same clock. Instead, I used a communication protocol that implements a handshake. The handshake protocol ensures the ESP32 will not send any new data if the python server isn’t done receiving the previous packet. Measuring the time between data packets received can be a pseudo-measurement of latency. This technique would be a conservative estimate since it assumes that the ESP32 instantly sends an additional packet once the handshake is received. I opted to use was TCP protocol since it is already implemented in the supplied ESP32 libraries.
TCP is widely used for internet communication, and efficiencies have evolved to increase throughput that may adversely affect our use case. One of these efficiencies is the Nagles Algorithm, which reduces the number of packets sent by concatenating multiple packets. This is enabled by default in the ESP32 WiFi layer and must be disabled to get accurate latency measurements. Another important step is to limit the TCP receive buffer size on the python server to be the same size as the data being sent. If this step is omitted, the buffer may fill up with multiple packets over a large delay and be read rapidly, giving false readings.
For this test, I used the ESP-32-DevKitC-VB to send a 16-byte packet to a constantly polling python server and measured the time between packets for 60 seconds.