1

我刚刚使用 Arduino 创建了 CoAP 客户端,并且能够将有效负载(“hello”)发送到 coap 浏览器(从 mozilla 浏览器安装)。我可以在浏览器中看到它,它接收。

现在我需要创建自己的 |Nodejs 服务器来从 Arduino 客户端接收我的有效负载(说“你好”)。我怎样才能实现它?

服务器

var coap        = require('coap');
    var server      = coap.createServer();

// At this point, I checked from mozilla coap browser, sent "hello" and I am able to receive the HEX values. Same way, I tried to send it from Arduino, but did not print anything
    server.on('request', function(req, res) {
       console.log(req.payload);
    })

    // the default CoAP port is 5683
    server.listen(function() {
        var req = coap.request('coap://localhost');
        console.log('Listening on : 5683')

        req.on('response', function(res) {
            res.pipe(process.stdout);
        });

        req.end()
    });

Arduino

void loop() {
  // send GET or PUT coap request to CoAP server.
  // To test, use libcoap, microcoap server...etc
   int msgid = coap.put(IPAddress(192,168,0,11), 5683, "light","1");
  Serial.println("Send Request");
  //int msgid1 = coap.get(IPAddress(192, 168, 0, 11), 5683, "time");

  delay(1000);
  coap.loop();
}
4

1 回答 1

0

在 Arduino 上,您应该在固件中(而不是在节点中)实现一个 coap 服务器。

你在使用这个库吗?如果是这样,那么您应该特别检查这个示例,它从以太网外围设备读取,解析数据包,然后做出相应的响应。

伪代码:

udp.setup()

while true
  p = udp.read()
  if(p == SUCCESSFUL_UDP_READ_FLAG)
    parsed = p.parse()
    if(parsed matches some condition)
      udp.respond(message regarding condition)

这里还有另一个带有 2 个端点的示例服务器。

重要的部分是:

内部void setup()

coap.add_resource(&aSensor);
coap.add_resource(&bSensor);

然后在里面void loop()

coap.handler();
于 2017-03-01T19:49:42.080 回答