I'm developing device that have a UDP socket open only to receive broadcast packets on one port (7890 to be exact). The problem is that the data losses are high - around 90%. My test setup is:
- ESP32 - connected to WiFi network with open UDP receing task (code belowe)
- PC connected to the same netwer via LAN with UDP terminal set to brodacast to remote: 192.168.10.255:7890
- Mobile phone connected to WiFi with UDP terminal set to brodacast to remote: 192.168.10.255:7890
I know that UDP does not guarantee the delivery but 10% efficiency seems for me to be super low, especially when it seems that there is no problem with busy network because PC and mobile received the data all the time.
Do you have any suggestion to the code or some setting that can be changed in menu config ?
At the moment my application have only two tasks:
+WiFi Task that after connection is just waiting for event
+UDP Task that the code is below
Code: Select all
#define PORT_NUMBER 7890
#define BUFLEN 100
void udp_task(void *pvParameter)
{
struct sockaddr_in clientAddress;
struct sockaddr_in serverAddress;
struct sockaddr_in si_other;
unsigned int slen = sizeof(si_other);
unsigned int recv_len;
char buf[BUFLEN];
int sock;
printf("UDP Task: Opening..\n");
int ret;
ret = UDP_List_Open(&clientAddress, &serverAddress, &sock);
if(ret == 0)
{
printf("UDP Task: Open\n");
}
else
{
printf("UDP Task: Can't open\n");
}
while(1)
{
memset(buf,0,100);
if ((recv_len = recvfrom(sock, buf, 100, 0, (struct sockaddr *) &si_other, &slen)) == -1)
{
printf("UDP error\n");
break;
}
sendto(sock, buf, recv_len, 0, (struct sockaddr *)&si_other, sizeof(si_other));
printf("UDP Task: Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
printf("UDP Task: Data: %s -- %d\n" , buf, recv_len); //recv_len sizeRead
}
while(1)
{
vTaskDelay(100 / portTICK_RATE_MS);
}
}
int UDP_List_Open(struct sockaddr_in* clientAddress, struct sockaddr_in* serverAddress, int* sock)
{
// Create a socket that we will listen upon.
*sock = socket(AF_INET, SOCK_DGRAM, 0);
if (*sock < 0)
{
printf("UDP List Open: Socket error\n");
return 1;
}
// Bind our server socket to a port.
serverAddress->sin_family = AF_INET;
serverAddress->sin_addr.s_addr = htonl(INADDR_ANY);//inet_addr("255.255.255.255");//
serverAddress->sin_port = htons(PORT_NUMBER);
int rc = bind(*sock, serverAddress, sizeof(*serverAddress));
if (rc < 0)
{
printf("UDP List Open: Bind error\n");
return 2;
}
return 0;
}