STM32 LWIP netconn_write in the cycle

2.9k views Asked by At

I've taken a project LwIP_HTTP_Server_Netconn_RTOS (STM32CubeMX) and changed TCP server code to shown down here. But at the client side i get result like this:

S: SET / Num: 1 Num: 6 Num: 6 Num: 6 Num: 6 Num: 7 Num: 7

What am i doing wrong?

void http_server_serve(struct netconn *conn)
{
struct netbuf *inbuf;
char* buf;
u16_t buflen;
size_t len;
unsigned int call_times = 0;

#define SIZE_ARRAY 21
char data[SIZE_ARRAY]={0};

while(netconn_recv(conn, &inbuf) == ERR_OK)
{
    netbuf_data(inbuf, (void**)&buf, &buflen);

    if ((buflen >=5) && (strncmp(buf, "SET /", 5) == 0))
    {
        for(int i=0;i<7;i++)
        {
            if(conn->state == NETCONN_NONE)
            {
                sprintf(data, " Num: %d\n", ++call_times);
                len = strlen(data);
                printf(" Num: %d\n", call_times);
                netconn_write(conn, (const unsigned char*)(data), (size_t)len, NETCONN_NOFLAG);
            }
        }
        netbuf_delete(inbuf);
    }
}

netconn_close(conn);
netbuf_delete(inbuf);
}
1

There are 1 answers

0
Freddie Chopin On

See this unofficial wiki of lwIP about netconn_write():

http://lwip.wikia.com/wiki/Netconn_write

err_t netconn_write ( struct netconn * aNetConn, const void * aData, size_t aSize, u8_t aApiFlags );

[...]

aApiFlags : either of

  • NETCONN_NOCOPY if the data is stable for the time of the transmission (static data or heap)
  • NETCONN_COPY if the data is not stable for the time of the transmission (stack)

Your first mistake is then to pass NETCONN_NOFLAG, which is not allowed. Most likely NETCONN_NOFLAG is numerically equal to NETCONN_NOCOPY. In that case lwIP will send data directly from your buffer, but this will be done "in background". When netconn_write(..., NETCONN_NOCOPY) returns, you must NOT modify the buffer you passed until the transmission is complete. Because you modify it during an ongoing transmission, you get wrong results at the receiving side.

In your case it would be pretty hard to get the info that the transmission is complete - this can be done only with callback. Even if you did that, this would give you no benefit at all, as you'd have to just wait for the "transmission complete" event anyway. So the best option here is to just use NETCONN_COPY.