coapjs / node-coap

CoAP - Node.js style
MIT License
528 stars 154 forks source link

Efento NB-Iot Coap Server #384

Closed robertsLando closed 4 months ago

robertsLando commented 4 months ago

I was looking for a way to convert this python script in NodeJS. I never used Coap protocol so based on a quick overview it seems to:

  1. Subscribe to requests on some paths
  2. Takes the required informations from them
  3. Stores the info in the db (this is not something I'm interested)
  4. Sends a response with some parameters.

What leaves me with more questions is the way they send the response as I cannot find a way to set all those informations in the actual response:

 def create_response(self, request_message_type, token, code, payload, ):
        if request_message_type == aiocoap.NON:

            return aiocoap.NoResponse
        else:
            # returning "ACK" and response payload to the sensor
            response = aiocoap.Message(mtype=aiocoap.ACK, code=code,
                                       token=token, payload=payload)

            logger.info(" response: " + str(response) + " payload: " + str(response.payload.hex()))
            return response

How can I create the same response with your server?

Thanks in advance

JKRhb commented 4 months ago

Hi @robertsLando, thank you opening this issue! One approach to set the information for the response in the request handler could like this:

const coap = require("coap")
const server = coap.createServer()

server.on('request', (req, res) => {
    const payload = "Hello World!"
    res.code = "2.05"
    res.end(payload)
})

server.listen(() => {
    console.log('server started')
})

In node-coap, the token and message type are set automatically, so you don't need to touch those.

I think the code you've posted above got the handling of non-confirmable messages (the request_message_type == aiocoap.NON part) a bit wrong, so this case doesn't really need to be handled separately, if I am not mistaken – with the default configuration, the server will just acknowledge all requests in so-called "piggybacked" response that both contains an acknowledgement and the actual response.

So to summarize, you should be able to keep this fairly simple :) I hope that I was able to help you out a bit, otherwise please me know and feel free to ask any question that you might have :)

robertsLando commented 4 months ago

@JKRhb Thanks a lot for your suggestion! I will try it out and let you know, closing for now 🙏🏼