How to use @node-wot/core - 10 common examples

To help you get started, we’ve selected a few @node-wot/core 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 eclipse / thingweb.node-wot / packages / binding-mqtt / src / mqtt-broker-server.ts View on Github external
}
        );

        let href = this.brokerURI + topic;
        let form = new TD.Form(href, ContentSerdes.DEFAULT);
        form.op = ["observeproperty", "unobserveproperty"];
        thing.properties[propertyName].forms.push(form);
        console.log(`MqttBrokerServer at ${this.brokerURI} assigns '${href}' to property '${propertyName}'`);
      }

      for (let actionName in thing.actions) {
        let topic = "/" + encodeURIComponent(name) + "/actions/" + encodeURIComponent(actionName);
        this.broker.subscribe(topic);

        let href = this.brokerURI + topic;
        let form = new TD.Form(href, ContentSerdes.DEFAULT);
        form.op = ["invokeaction"];
        thing.actions[actionName].forms.push(form);
        console.log(`MqttBrokerServer at ${this.brokerURI} assigns '${href}' to Action '${actionName}'`);
      }

      // connect incoming messages to Thing
      this.broker.on("message", (receivedTopic: string, payload: string, packet: IPublishPacket) => {

        // route request
        let segments = receivedTopic.split("/");

        if (segments.length === 4 ) {
          console.log(`MqttBrokerServer at ${this.brokerURI} received message for '${receivedTopic}'`);
          let thing = this.things.get(segments[1]);
          if (thing) {
            if (segments[2] === "actions") {
github eclipse / thingweb.node-wot / packages / cli / src / cli.ts View on Github external
argv.splice(i, 1);
        i--;

    } else if (argv[i].match(/^(-i|-ib|--inspect(-brk)?(=([a-z]*|[\d .]*):?(\d*))?|\/i|\/ib)$/i)) {
        let matches = argv[i].match(/^(-i|-ib|--inspect(-brk)?(=([a-z]*|[\d .]*):?(\d*))?|\/i|\/ib)$/i)
        debug = {
            shouldBreak: matches[2] === "-brk" || matches[1] === "-ib" || matches[1] === "/ib",
            host: matches[4] ? matches[4] : "127.0.0.1",     // default host
            port: matches[5] ? parseInt(matches[5]) : 9229   // default port
        }

        argv.splice(i, 1);
        i--;

    } else if (argv[i].match(/^(-v|--version|\/c)$/i)) {
        console.log( require('@node-wot/core/package.json').version );
        process.exit(0);

    } else if (argv[i].match(/^(-h|--help|\/?|\/h)$/i)) {
        console.log(`Usage: wot-servient [options] [SCRIPT]...
       wot-servient
       wot-servient examples/scripts/counter.js examples/scripts/example-event.js
       wot-servient -c counter-client.js
       wot-servient -f ~/mywot.conf.json examples/testthing/testthing.js

Run a WoT Servient in the current directory.
If no SCRIPT is given, all .js files in the current directory are loaded.
If one or more SCRIPT is given, these files are loaded instead of the directory.
If the file 'wot-servient.conf.json' exists, that configuration is applied.

Options:
  -v,  --version                   display node-wot version
github eclipse / thingweb.node-wot / packages / binding-coap / src / coap-server.ts View on Github external
private handleRequest(req: any, res: any) {
    console.log(`CoapServer on port ${this.getPort()} received ${req.method} ${req.url}`
      + ` from ${req.rsinfo.address} port ${req.rsinfo.port}`);
    res.on('finish', () => {
      console.log(`CoapServer replied with ${res.code} to ${req.rsinfo.address} port ${req.rsinfo.port}`);
      // FIXME res.options is undefined, no other useful property to get Content-Format
      //logger.warn(`CoapServer sent Content-Format: '${res.options['Content-Format']}'`);
    });

    let requestUri = url.parse(req.url);
    let requestHandler = this.resources[requestUri.pathname];
    // TODO must be rejected with 4.15 Unsupported Content-Format, guessing not allowed
    let contentType = req.options['Content-Format'] ? req.options['Content-Format'] : ContentSerdes.DEFAULT;

    if (requestHandler === undefined) {
      res.code = '4.04';
      res.end('Not Found');
    } else {
      if (req.method === 'GET') {
        requestHandler.onRead()
          .then(content => {
            res.code = '2.05';
            if (!content.contentType) {
              console.warn(`CoapServer got no Media Type from '${requestUri.pathname}'`);
            } else {
              res.setOption('Content-Format', content.contentType);
            }
            // finish
            res.end(content.body);
github eclipse / thingweb.node-wot / packages / binding-websockets / src / ws-server.ts View on Github external
res.writeHead(200);
      res.end();
      return;
    }

    let requestUri = url.parse(req.url);
    let requestHandler = this.resources[requestUri.pathname];
    let contentTypeHeader: string | string[] = req.headers["content-type"];
    let contentType: string = Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader;

    console.log(`HttpServer on port ${this.getPort()} received ${req.method} ${requestUri.pathname} from ${req.socket.remoteAddress} port ${req.socket.remotePort}`);
    
    // FIXME must be rejected with 415 Unsupported Media Type, guessing not allowed -> debug/testing flag
    if ((req.method === "PUT" || req.method === "POST") && (!contentType || contentType.length == 0)) {
      console.warn(`HttpServer on port ${this.getPort()} got no Media Type for ${req.method}`);
      contentType = ContentSerdes.DEFAULT;
    }

    if (requestHandler === undefined) {
      res.writeHead(404);
      res.end("Not Found");

    } else if ( (req.method === "PUT" || req.method === "POST")
              && ContentSerdes.get().getSupportedMediaTypes().indexOf(ContentSerdes.getMediaType(contentType))<0) {
      res.writeHead(415);
      res.end("Unsupported Media Type");

    } else {
      if (req.method === "GET" && (requestHandler.getType()==="Property" || requestHandler.getType()==="Asset" ||(requestHandler.getType()==="TD"))) {
        requestHandler.onRead()
          .then(content => {
            if (!content.contentType) {
github eclipse / thingweb.node-wot / packages / binding-http / src / http-server.ts View on Github external
res.writeHead(200);
      res.end();
      return;
    }

    let requestUri = url.parse(req.url);
    let requestHandler = this.resources[requestUri.pathname];
    let contentTypeHeader: string | string[] = req.headers["content-type"];
    let mediaType: string = Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader;

    console.log(`HttpServer on port ${this.getPort()} received ${req.method} ${requestUri.pathname} from ${req.socket.remoteAddress} port ${req.socket.remotePort}`);
    
    // FIXME must be rejected with 415 Unsupported Media Type, guessing not allowed -> debug/testing flag
    if ((req.method === "PUT" || req.method === "POST") && (!mediaType || mediaType.length == 0)) {
      console.warn(`HttpServer on port ${this.getPort()} got no Media Type for ${req.method}`);
      mediaType = ContentSerdes.DEFAULT;
    }

    if (requestHandler === undefined) {
      res.writeHead(404);
      res.end("Not Found");

    } else if ( (req.method === "PUT" || req.method === "POST")
              && ContentSerdes.get().getSupportedMediaTypes().indexOf(ContentSerdes.get().isolateMediaType(mediaType))<0) {
      res.writeHead(415);
      res.end("Unsupported Media Type");

    } else {
      if (req.method === "GET" && (requestHandler.getType()==="Property" || requestHandler.getType()==="Asset" ||(requestHandler.getType()==="TD"))) {
        requestHandler.onRead()
          .then(content => {
            if (!content.mediaType) {
github eclipse / thingweb.node-wot / packages / binding-http / src / http-server.ts View on Github external
res.writeHead(200);
                res.end(content.body);
              }
            })
            .catch((err) => {
              console.error(`HttpServer on port ${this.getPort()} got internal error on invoke '${requestUri.pathname}': ${err.message}`);
              res.writeHead(500);
              res.end(err.message);
            });
        });

      } else if (requestHandler instanceof EventResourceListener) {
        // NOTE: Using Keep-Alive does not work well with NodeJS HTTP client because of socket pooling :/

        // FIXME get supported content types from EventResourceListener
        res.setHeader("Content-Type", ContentSerdes.DEFAULT);
        res.writeHead(200);
        let subscription = requestHandler.subscribe({
          next: (content) => {
            // send event data
            res.end(content.body);
          },
          complete: () => res.end()
        });
        res.on("finish", () => {
          console.debug(`HttpServer on port ${this.getPort()} closed Event connection`);
          subscription.unsubscribe();
        });
        res.setTimeout(60*60*1000, () => subscription.unsubscribe());

      } else if (req.method === "DELETE") {
        requestHandler.onUnlink()
github eclipse / thingweb.node-wot / packages / binding-websockets / src / ws-server.ts View on Github external
}
                res.writeHead(200);
                res.end(content.body);
              }
            })
            .catch((err) => {
              console.error(`HttpServer on port ${this.getPort()} got internal error on invoke '${requestUri.pathname}': ${err.message}`);
              res.writeHead(500);
              res.end(err.message);
            });
        });

      } else if (requestHandler instanceof EventResourceListener) {
        res.setHeader("Connection", "Keep-Alive");
        // FIXME get supported content types from EventResourceListener
        res.setHeader("Content-Type", ContentSerdes.DEFAULT);
        res.writeHead(200);
        let subscription = requestHandler.subscribe({
          next: (content) => res.end(content.body),
          complete: () => res.end()
        });
        res.on("close", () => {
          console.warn(`HttpServer on port ${this.getPort()} lost Event connection`);
          subscription.unsubscribe();
        });
        res.on("finish", () => {
          console.warn(`HttpServer on port ${this.getPort()} closed Event connection`);
          subscription.unsubscribe();
        });
        res.setTimeout(60*60*1000, () => subscription.unsubscribe());

      } else if (req.method === "DELETE") {
github eclipse / thingweb.node-wot / packages / binding-http / src / http-server.ts View on Github external
let mediaType: string = Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader;

    console.log(`HttpServer on port ${this.getPort()} received ${req.method} ${requestUri.pathname} from ${req.socket.remoteAddress} port ${req.socket.remotePort}`);
    
    // FIXME must be rejected with 415 Unsupported Media Type, guessing not allowed -> debug/testing flag
    if ((req.method === "PUT" || req.method === "POST") && (!mediaType || mediaType.length == 0)) {
      console.warn(`HttpServer on port ${this.getPort()} got no Media Type for ${req.method}`);
      mediaType = ContentSerdes.DEFAULT;
    }

    if (requestHandler === undefined) {
      res.writeHead(404);
      res.end("Not Found");

    } else if ( (req.method === "PUT" || req.method === "POST")
              && ContentSerdes.get().getSupportedMediaTypes().indexOf(ContentSerdes.get().isolateMediaType(mediaType))<0) {
      res.writeHead(415);
      res.end("Unsupported Media Type");

    } else {
      if (req.method === "GET" && (requestHandler.getType()==="Property" || requestHandler.getType()==="Asset" ||(requestHandler.getType()==="TD"))) {
        requestHandler.onRead()
          .then(content => {
            if (!content.mediaType) {
              console.warn(`HttpServer on port ${this.getPort()} got no Media Type from ${req.socket.remoteAddress} port ${req.socket.remotePort}`);
            } else {
              res.setHeader("Content-Type", content.mediaType);
            }
            res.writeHead(200);
            res.end(content.body);
          })
          .catch(err => {
github eclipse / thingweb.node-wot / packages / binding-mqtt / src / mqtt-broker-server.ts View on Github external
(data) => {
            let content;
            try {
              content = ContentSerdes.get().valueToContent(data, event.data);
            } catch(err) {
              console.warn(`HttpServer on port ${this.getPort()} cannot process data for Event '${eventName}: ${err.message}'`);
              // subscription.unsubscribe();
              thing.unsubscribeEvent(eventName);
              return;
            }
            // send event data
            console.log(`MqttBrokerServer at ${this.brokerURI} publishing to Event topic '${eventName}' `);
            this.broker.publish(topic, content.body);
          }
        );
github eclipse / thingweb.node-wot / packages / binding-websockets / src / ws-server.ts View on Github external
let contentType: string = Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader;

    console.log(`HttpServer on port ${this.getPort()} received ${req.method} ${requestUri.pathname} from ${req.socket.remoteAddress} port ${req.socket.remotePort}`);
    
    // FIXME must be rejected with 415 Unsupported Media Type, guessing not allowed -> debug/testing flag
    if ((req.method === "PUT" || req.method === "POST") && (!contentType || contentType.length == 0)) {
      console.warn(`HttpServer on port ${this.getPort()} got no Media Type for ${req.method}`);
      contentType = ContentSerdes.DEFAULT;
    }

    if (requestHandler === undefined) {
      res.writeHead(404);
      res.end("Not Found");

    } else if ( (req.method === "PUT" || req.method === "POST")
              && ContentSerdes.get().getSupportedMediaTypes().indexOf(ContentSerdes.getMediaType(contentType))<0) {
      res.writeHead(415);
      res.end("Unsupported Media Type");

    } else {
      if (req.method === "GET" && (requestHandler.getType()==="Property" || requestHandler.getType()==="Asset" ||(requestHandler.getType()==="TD"))) {
        requestHandler.onRead()
          .then(content => {
            if (!content.contentType) {
              console.warn(`HttpServer on port ${this.getPort()} got no Media Type from ${req.socket.remoteAddress} port ${req.socket.remotePort}`);
            } else {
              res.setHeader("Content-Type", content.contentType);
            }
            res.writeHead(200);
            res.end(content.body);
          })
          .catch(err => {