Sending and receiving UDP packets in LwIP over same connection?

4.7k views Asked by At

I'm developing an application that should be able to asynchronously transmit and receive UDP messages with the same port number and am a little confused about the best way of doing this. I'm using LwIP and FreeRTOS on a STM32 platform and am wanting to use the netconn api.

My application should:

  • Transmit messages after a certain ISR fires. I have it setup so the ISR releases a semaphore, which my UDP task consumes.
  • Receive messages all the time

If I were developing this on Linux, I think it'd make sense to have one thread for send and one to receive, or maybe use the select OS call. As far as I can tell, neither of these are feasible with LwIP.

The only option I've thought of is to do something like this in my UDP task.

void my_task(void)
{
    // setup netconn connection here
    netconn_set_recvtimeout(conn, 1);

    while (1) 
    {
        // Only wait 1ms to take the semaphore
        if(xSemaphoreTake(isr_semaphore, 1) == pdTRUE)
        {
            netconn_send(conn, nbuf);
        }

        // Only block for 1ms to receive a UDP message
        if(netconn_recv(conn, mybuf) == ERR_OK)
        {
            //process incoming data
        }
    }
}

However this seems fairly ineloquent to me as I'm wasting 1ms for each call. Is there a better way to achieve the same thing? I feel like this must be a really common requirement, yet I don't see any examples of this out there.

2

There are 2 answers

0
K. Koovalsky On

As LWIP documentation mentions netconn API is sequential, so blocking API.
If you want to make it asynchronous you should use raw API which is callback based.

0
ajk On

Since you are using FreeRTOS, create two separate tasks to send and receive. Set the priority of the sending task higher than that of the listener. In other words, create a client and a server task.