How to use coap - 10 common examples

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 CommonGarden / Grow-IoT / imports / api / coap / coap.js View on Github external
import coap from 'coap';
import url from 'url';
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import Fiber from 'fibers';
import _ from 'underscore';
import { Match } from 'meteor/check';

const server = coap.createServer();

server.on('request', function(req, res) {
  // console.log(req)
  Fiber(function () {
    let urlParts = url.parse(req.url, true);
    let method = urlParts.pathname.replace(/\//g, '');
    let payload = JSON.parse(req.payload.toString());

    console.log(urlParts);
    console.log(method);
    console.log(payload);

    let auth = {
      uuid: payload.uuid,
      token: payload.token
    };
github Alliasd / ELIoT / lib / init.js View on Github external
init.setupNode = function (cn, devResrcs) {
    var maxLatency = (cn._config.reqTimeout - 47)/ 2,
        so = cn.getSmartObject();

    coap.updateTiming({
        maxLatency: maxLatency
    });

    coap.registerFormat('application/json', 11543);     // Leshan JSON Numeric Content-Formats
    coap.registerFormat('application/tlv', 11542);	// Leshan TLV Content-Format

    so.init('lwm2mServer', 0, {                         // oid = 1
        shortServerId: 'unknown',                       // rid = 0
        lifetime: cn.lifetime,                          // rid = 1
        defaultMinPeriod: cn._config.defaultMinPeriod,  // rid = 2
        defaultMaxPeriod: cn._config.defaultMaxPeriod   // rid = 3
    });

    so.init('device', 0, {                         // oid = 3
        manuf: devResrcs.manuf || 'sivann',        // rid = 0
        model: devResrcs.model || 'cnode-01',      // rid = 1
        serial: devResrcs.serial || 'c-0000',      // rid = 2
        firmware: devResrcs.firmware || 'v1.0',    // rid = 3
        devType: devResrcs.devType || 'generic',   // rid = 17
        hwVer: devResrcs.hwVer || 'v1.0',          // rid = 18
github PeterEB / coap-node / lib / init.js View on Github external
init.setupNode = function (cn, devResrcs) {
    var propWritable = { writable: true, enumerable: false, configurable: false },
        maxLatency = (cn._config.reqTimeout - 47)/ 2,
        so = cn.getSmartObject();

    coap.updateTiming({
        maxLatency: maxLatency
    });

    coap.registerFormat('application/tlv', 11542);      // Leshan TLV binary Content-Formats
    coap.registerFormat('application/json', 11543);     // Leshan JSON Numeric Content-Formats

    so.init('device', 0, {                         // oid = 3
        manuf: devResrcs.manuf || 'sivann',        // rid = 0
        model: devResrcs.model || 'cnode-01',      // rid = 1
        serial: devResrcs.serial || 'c-0000',      // rid = 2
        firmware: devResrcs.firmware || '1.0',     // rid = 3
        devType: devResrcs.devType || 'generic',   // rid = 17
        hwVer: devResrcs.hwVer || '1.0',           // rid = 18
        swVer: devResrcs.swVer || '1.0',           // rid = 19
        availPwrSrc: devResrcs.availPwrSrc || 0,
        pwrSrcVoltage: devResrcs.pwrSrcVoltage || 100
    });

    so.init('connMonitor', 0, {     // oid = 4
        ip: cn.ip,                  // rid = 4
github PeterEB / coap-node / lib / init.js View on Github external
init.setupNode = function (cn, devResrcs) {
    var propWritable = { writable: true, enumerable: false, configurable: false },
        maxLatency = (cn._config.reqTimeout - 47)/ 2,
        so = cn.getSmartObject();

    coap.updateTiming({
        maxLatency: maxLatency
    });

    coap.registerFormat('application/tlv', 11542);      // Leshan TLV binary Content-Formats
    coap.registerFormat('application/json', 11543);     // Leshan JSON Numeric Content-Formats

    so.init('device', 0, {                         // oid = 3
        manuf: devResrcs.manuf || 'sivann',        // rid = 0
        model: devResrcs.model || 'cnode-01',      // rid = 1
        serial: devResrcs.serial || 'c-0000',      // rid = 2
        firmware: devResrcs.firmware || '1.0',     // rid = 3
        devType: devResrcs.devType || 'generic',   // rid = 17
        hwVer: devResrcs.hwVer || '1.0',           // rid = 18
        swVer: devResrcs.swVer || '1.0',           // rid = 19
        availPwrSrc: devResrcs.availPwrSrc || 0,
        pwrSrcVoltage: devResrcs.pwrSrcVoltage || 100
    });

    so.init('connMonitor', 0, {     // oid = 4
        ip: cn.ip,                  // rid = 4
        routeIp: 'unknown'          // rid = 5         
github Alliasd / ELIoT / lib / init.js View on Github external
init.setupNode = function (cn, devResrcs) {
    var maxLatency = (cn._config.reqTimeout - 47)/ 2,
        so = cn.getSmartObject();

    coap.updateTiming({
        maxLatency: maxLatency
    });

    coap.registerFormat('application/json', 11543);     // Leshan JSON Numeric Content-Formats
    coap.registerFormat('application/tlv', 11542);	// Leshan TLV Content-Format

    so.init('lwm2mServer', 0, {                         // oid = 1
        shortServerId: 'unknown',                       // rid = 0
        lifetime: cn.lifetime,                          // rid = 1
        defaultMinPeriod: cn._config.defaultMinPeriod,  // rid = 2
        defaultMaxPeriod: cn._config.defaultMaxPeriod   // rid = 3
    });

    so.init('device', 0, {                         // oid = 3
        manuf: devResrcs.manuf || 'sivann',        // rid = 0
        model: devResrcs.model || 'cnode-01',      // rid = 1
        serial: devResrcs.serial || 'c-0000',      // rid = 2
        firmware: devResrcs.firmware || 'v1.0',    // rid = 3
        devType: devResrcs.devType || 'generic',   // rid = 17
        hwVer: devResrcs.hwVer || 'v1.0',          // rid = 18
        swVer: devResrcs.swVer || 'v1.0',          // rid = 19
github avency / coap-cli / index.js View on Github external
})
}

var defaultAckTimeout = 30.0
if (program.ackTimeout) {
  defaultAckTimeout = program.ackTimeout
}

var coapTiming = {
  ackTimeout: defaultAckTimeout,
  ackRandomFactor: 1.0,
  maxRetransmit: 5,
  maxLatency: 2,
  piggybackReplyMs: 10
}
coap.updateTiming(coapTiming)

req.on('response', function (res) {
  var endTime = new Date()
  if (program.showTiming) {
    console.log('Request took ' + (endTime.getTime() - startTime.getTime()) + ' ms')
  }

  // print only status code on empty response
  if (!res.payload.length && !program.quiet) {
    process.stderr.write('\x1b[1m(' + res.code + ')\x1b[0m\n')
  }

  res.pipe(through(function addNewLine (chunk, enc, callback) {
    if (!program.quiet) {
      process.stderr.write('\x1b[1m(' + res.code + ')\x1b[0m\t')
    }
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