ESP32 - UDP broadcaster/ receiver with native LwIP library

大兔子大兔子 提交于 2019-12-23 18:00:33

问题


I'm building a distributed application with the ESP32 (a great platform btw) where all participants should communicate over UDP in it's simplest form: sending messages via broadcast and listening to all messages floating around. Each participant filters the relevant messages by itself.

So far, I have the following initialization routine:

int lavor_wifi_openUDPsocket(){
    // Create a socket
    int sckt = socket(AF_INET, SOCK_DGRAM, 0);
    if ( sckt < 0 ){
        printf("socket call failed");
        exit(0);
    }

    // Prepare binding to port
    struct sockaddr_in sLocalAddr;
    // Initialize the address
    memset((char *)&sLocalAddr, 0, sizeof(sLocalAddr));

    sLocalAddr.sin_family = AF_INET;
    sLocalAddr.sin_len = sizeof(sLocalAddr);
    sLocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    sLocalAddr.sin_port = UDP_SOCKET_PORT;

    bind(sckt, (struct sockaddr *)&sLocalAddr, sizeof(sLocalAddr));

    return sckt;
}

Then, a message would be send with:

void lavor_wifi_sendUDPmsg(int sckt, char* msg, int len){
    // Prepare the address to sent to via BROADCAST
    struct sockaddr_in sDestAddr;
    // Initialize the address
    // memset((char *)&sDestAddr, 0, sizeof(sDestAddr));

    sDestAddr.sin_family = AF_INET;
    sDestAddr.sin_len = sizeof(sDestAddr);
    sDestAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
    sDestAddr.sin_port = UDP_SOCKET_PORT;

    if(sendto(sckt, msg, len, 0, (struct sockaddr *)&sDestAddr, sizeof(sDestAddr)) < len){
         printf("UDP message couldn't be sent.");
    }
}

And finally, receiving messages would work like this:

void lavor_wifi_processor(void* sckt){
    int nbytes;
    char buffer[UDP_BUFF_LEN];
    // Listen for incoming messages as long as the socket is open
    while(1){   // TO DO: Test if socket open
        // Try to read new data arrived at the socket
        nbytes = recv(*((int *)sckt), buffer, sizeof(buffer), 0);
    ...

But even if I just try to call the above initialization function, the ESP goes wild and throws one Guru Meditation error after another.

Does anyone has experience with UDP communication in the descripted way?


回答1:


I got UDP with ESP32/UDP/LWIP to work with this example:

https://github.com/Ebiroll/qemu_esp32/blob/master/examples/19_udp

Note that send_thread() is not started until we have received an ip address.

However it also might also be that you need v2.0 of esp-idf. I also got Guru Meditation errors with latest version.



来源:https://stackoverflow.com/questions/44399443/esp32-udp-broadcaster-receiver-with-native-lwip-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!