Search code examples
node.jsesp32coap

CoAP server on ESP32 and Node client


I'm trying to build a sysyem with the ESP32 and some sensors. I created the CoAP server on the ESP32 using this library. I tested the server with both coap-client on mint and with copper installed on chrome, and in both cases the GET obtains what i expect. When trying to invoke the GET with this lilbrary following the example what happens is that the request arrives to the server, but it seems like no response is received by the Node bit. This is the Node bit

const req = coap.request('coap://192.168.1.229/sensor/info')

req.on('response', (res) => {
    res.pipe(process.stdout)
    res.on('end', () => {
    process.exit(0)
    })
})
req.end()

that is basically the example, and this is the ESP32 callback for the GET

void callback_coap_info(CoapPacket &packet, IPAddress ip, int port){
    Serial.println("Coap request in info");
    coap.sendResponse(ip, port, packet.messageid, buffer_id);
}

buffer_id is the response that is formatted in JSON, and from coap-client it looks like that json response.

EDIT: I was asked to provide a capture so here there is a wireshark capture for the IP of my ESP32. The first two rows are the request created with libCOAP (the same thing used in the other screen) and the response to that, while the other rows are the ones that are created by using the coap request posted above. It seems to me like the request is received by the ESP32 and the answer is similar to the one received in libCOAP.


Solution

  • Ok so Achim Kraus actually helped me a lot by making me doing the packet capture. Analyzing the request sent with the js bit it is possible to see a field token being used, which i didn't consider when sending back the answer. I updated the callback inside the ESP and now the code looks like that

    void callback_coap_info(CoapPacket &packet, IPAddress ip, int port){
        Serial.println("Coap request in info");
        coap.sendResponse(ip, port, packet.messageid, buffer_temp_hum, 
            strlen(buffer_temp_hum), COAP_CONTENT, COAP_TEXT_PLAIN, 
            packet.token, packet.tokenlen);
    }
    

    The library has different versions of sendResponse, and the one that is needed in this case is the one with all the possible fields set in which it is possible to specify the token. This now works both with libCOAP and with the js code provided. Thank you a lot for the idea of capturing the packets.