How to use the coap.request function in coap

To help you get started, we’ve selected a few coap examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pangpangshui / NBIot-Cloud-Server / NBIotServer / routes / Iot / CoAPServer.js View on Github external
}

                        // console.log(HexPort);

                        agen = new coap.Agent({type:"udp4", port:5683});
                        var requestOptions = {
                            host: req.rsinfo.address,
                            port: req.rsinfo.port,
                            pathname: '/t/d',
                            method: 'GET',
                            confirmable: true,
                            observe: true,
                            retrySend: 5,
                            agent: agen
                        };
                        var reqCoap = coap.request(requestOptions);
                        // reqCoap.setOption("observe", "0");
                        reqCoap.setOption("Uri-Port", Buffer.from(HexPort));
                        reqCoap.end();
                        reqCoap.on('response', (resp) => {
                            if (resp.code == '2.05') {
                                //返回给前端显示设备上线,对应的是响应码为2.05的ASK响应
                                // console.log((response));
                                response.json({
                                    status: '2'
                                });
                                response.end();
                            }
                            global.sendCoapFlag = 1;
                            resp.pipe(process.stdout); //只有该句可输出上行payload, 此处抓取的是第二个响应,即non响应(不是请求), 第一个是ASK响应
                            resp.setEncoding('utf8');
                            resp.on('data', (receCoAPData) =>{
github IoTKETI / Mobius / mobius / responder.js View on Github external
function request_noti_coap(nu, bodyString, bodytype, xm2mri) {
    var options = {
        host: url.parse(nu).hostname,
        port: url.parse(nu).port,
        pathname: url.parse(nu).path,
        method: 'post',
        confirmable: 'false',
        options: {
            'Accept': 'application/'+bodytype,
            'Content-Type': 'application/'+bodytype,
            'Content-Length' : bodyString.length
        }
    };

    var responseBody = '';
    var req = coap.request(options);
    req.setOption("256", new Buffer(usecseid));      // X-M2M-Origin
    req.setOption("257", new Buffer(xm2mri));    // X-M2M-RI
    req.on('response', function (res) {
        res.on('data', function () {
            responseBody += res.payload.toString();
        });

        res.on('end', function () {
            console.log('----> [nonblocking-async-coap] response for notification through coap  ' + res.code);
        });
    });

    console.log('<---- [nonblocking-async-coap] request for notification through coap with ' + bodytype);

    req.write(bodyString);
    req.end();
github w3c / web-of-things-framework / examples / coap_demo / simulator.js View on Github external
function coap_send(data) {
    var req = coap.request('coap://localhost'); // the WoT server listen on dafault port
    
    req.write(JSON.stringify(data));
    
    req.on('response', function (res) {
        try {
            if (res && res.payload && res.payload.length) {
                //var msg = JSON.parse(res.payload.toString());
                logger.debug("CoAP server response: " +  res.payload.toString());
            }
            res.on('end', function () {
            })
        }
        catch (e) {
            logger.error("coap send error: " + e.message);
        }
    })
github mcollina / ponte / benchmark / many-to-one / mqtt-to-coap.js View on Github external
conn.connect({
                  protocolId: 'MQIsdp',
                  protocolVersion: 3,
                  clientId: "client" + publishers.length,
                  keepalive: 1000,
                  clean: true
                });
              }
  , next = function() {
             if (publishers.length < total) {
               mqtt.createConnection(1883, '127.0.0.1', created);
             }
           };

coap.request({
  method: "PUT",
  pathname: "/topics/hello"
}).end("done").on("response", function() {
  var listener = coap.request({
    pathname: "/topics/hello",
    observe: true
  }).end();

  listener.on("response", function(res) {
    var first = true
    next()
    
    res.on("data", function() {
      // the first one is the current state
      if (first) {
        first = false
github telefonicaid / lwm2m-node-lib / test / unit / testUtils.js View on Github external
return function (done) {
        var req = coap.request(requestUrl),
            rs = new Readable();

        libLwm2m2.setHandler(testInfo.serverInfo, 'registration',
            function(endpoint, lifetime, version, binding, payload, callback) {
                callback();
            });

        rs.push(payload);
        rs.push(null);
        rs.pipe(req);

        req.on('response', function(res) {
            res.code.should.equal(code);
            done();
        });
    };
github webofthings / webofthings.js / plugins / external / coapPlugin.js View on Github external
read: function () { //#B
      coap
        .request({ //#C
          host: 'localhost',
          port: 5683,
          pathname: '/co2',
          options: {'Accept': 'application/json'}
        })
        .on('response', function (res) { //#D
          console.info('CoAP response code', res.code);
          if (res.code !== '2.05')
            console.log("Error while contacting CoAP service: %s", res.code);
          res.pipe(bl(function (err, data) { //#E
            var json = JSON.parse(data);
            me.value = json.co2;
            showValue();
          }));
        })
github qnap-dev / qnap-qiot-sdks / nodejs / device / raspberrypi / examples / lib / coap-connect.js View on Github external
var publishByTopic = function publishByTopic(topic, value) {
    var jsonVal = JSON.stringify({
        value: value
    });

    var options = {};
    options.clientId = this.coapoptions.clientId;
    options.port = this.coapoptions.port;
    options.host = this.coapoptions.host;
    options.query = this.coapoptions.query;
    options.pathname = topic;
    options.method = 'PUT';

    var req = coap.request(options).end(jsonVal);
    req.on('response', function(res) {
        res.pipe(process.stdout);
        if (res.code == "2.04") //Success Code Handler
            console.log(" send message to [coap://" + options.host + ":" + options.port + '/' + options.pathname + ", value = " + jsonVal);
        else //Error Code Handler
            console.log("Error Code:  " + res.code);
    })
}
github mcollina / ponte / benchmark / many-to-one / coap-to-coap.js View on Github external
, publish = function() {
                  //print("publishing");
                  console.error("all client connected, sending the message");
                  start = Date.now();
                  
                  for (i = 0; i < total; i++)
                    coap.request({
                      method: "PUT",
                      pathname: "/topics/hello"
                    }).end("world")
                }
github CommonGarden / Grow-IoT / examples / coap / callthing.js View on Github external
const coap = require('coap');

var req = coap.request('coap://localhost/turn_on');

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

req.end()

var req2 = coap.request('coap://localhost/get?key=state');

req2.on('response', function(res2) {
  res2.pipe(process.stdout)
});

req2.end();
github phodal-archive / iot-editor / index.js View on Github external
ipc.on('coap', function(event, arg) {
		var coap    = require('coap');
		var server = 'coap://' + arg.coapServer + '/topics/' + arg.coapTopic;
		var req  = coap.request(server);

		req.on('response', function(res) {
			event.returnValue = {
				response: res.payload.toString()
			}
		});

		req.end();
	});