Hi everyone,
I am using Udp.receivePacket(packetBuffer,maxPacketSize) method to receive a stream of sensor data, however I seem to be getting a backlog of packets causing a delay.I have tried Udp.flush(); but the backlog still builds up.
Any advice would be much appreciated.
Thanks
Andy
How fast and how big are the packets? Using the code below, my Photon is reliable at receiving 250 packets of 64 bytes per second by UDP.
Moving up to 333 packets per second a few packets are dropped. At 500 packets per second, it’s a little worse. And at 1000 packets per second, packets are dropped left and right.
Incidentally, in my experience the outbound from the Photon network performance of both UDP and TCP is much, much higher than the inbound. The Photon makes a good sender of sensor data, but not as good of a receiver.
#include "Particle.h"
const size_t UDP_BUFFER_SIZE = 512;
const int UDP_PORT = 7123;
UDP udp;
uint8_t udpBuffer[UDP_BUFFER_SIZE+1];
void setup() {
Serial.begin(9600);
udp.begin(UDP_PORT);
Serial.printlnf("server=%s:%d", WiFi.localIP().toString().c_str(), UDP_PORT);
}
void loop() {
// receivePacket() is preferable to parsePacket()/read() because it saves a buffering step but more importantly
// it return an error code if an error occurs! This is important to reinitialize the listener on error.
int count = udp.receivePacket(udpBuffer, UDP_BUFFER_SIZE);
if (count > 0) {
// note: udpBuffer is actually 1 byte larger than UDP_BUFFER_SIZE to account for this
udpBuffer[count] = 0;
// IPAddress remoteAddr = udp.remoteIP();
// udpBuffer contains a sequence number as decimal number in ASCII, followed by 0 bytes to the packet size
Serial.printlnf("## %s", udpBuffer);
}
else
if (count == 0) {
// No packet
}
else {
Serial.printlnf("** error %d", count);
udp.begin(UDP_PORT);
}
}
thanks for the reply
The packets can be of varying size, up-to 573 bytes, the packet frequency is also variable. It ok for me to drop packets, is there a way to drop some or even all of them? Udp.flush() did not seem to have any effect?
The udp.flush()
method only works with udp.parsePacket()
and even then it only discards the packet currently being processed, so that would not help at all either.
If you want to discard all outstanding packets, however, just call udp.receivePacket()
in a loop until it returns a result <= 0. You can make it more efficient by passing a very small buffer, 1 byte works, because it will just discard the data in the buffer that is past the size of the buffer you passed in.
excellent guidance, thankyou