How to use node-coap-client - 10 common examples

To help you get started, we’ve selected a few node-coap-client 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-coap / src / coaps-client.ts View on Github external
let method: string = dflt;

    if (typeof form["coap:methodCode"] === "number") {
      console.log("CoapsClient got Form 'methodCode'", form["coap:methodCode"]);
      switch (form["coap:methodCode"]) {
        case 1: method = "get"; break;
        case 2: method = "post"; break;
        case 3: method = "put"; break;
        case 4: method = "delete"; break;
        default: console.warn("CoapsClient got invalid 'methodCode', using default", method);
      }
    }

    console.log(`CoapsClient sending ${method} to ${form.href}`);
    let req = coaps.request(
        form.href /* string */,
        method /* "get" | "post" | "put" | "delete" */,
        content ? content.body : undefined /* Buffer */
    );

    return req;
  }
}
github eclipse / thingweb.node-wot / packages / binding-coap / src / coaps-client.ts View on Github external
private generateRequest(form: CoapForm, dflt: string, content?: Content): any {
    
    // url only works with http*
    let requestUri = url.parse(form.href.replace(/$coaps/, "https"));
    coaps.setSecurityParams(requestUri.hostname, this.authorization );

    let method: string = dflt;

    if (typeof form["coap:methodCode"] === "number") {
      console.log("CoapsClient got Form 'methodCode'", form["coap:methodCode"]);
      switch (form["coap:methodCode"]) {
        case 1: method = "get"; break;
        case 2: method = "post"; break;
        case 3: method = "put"; break;
        case 4: method = "delete"; break;
        default: console.warn("CoapsClient got invalid 'methodCode', using default", method);
      }
    }

    console.log(`CoapsClient sending ${method} to ${form.href}`);
    let req = coaps.request(
github AlCalzone / node-tradfri-client / src / tradfri-client.ts View on Github external
private async updateResource(path: string, newObj: IPSOObject, reference: IPSOObject): Promise {

		const serializedObj = newObj.serialize(reference);

		// If the serialized object contains no properties, we don't need to send anything
		if (!serializedObj || Object.keys(serializedObj).length === 0) {
			log(`updateResource(${path}) > empty object, not sending any payload`, "debug");
			return false;
		}

		// get the payload
		let payload: string | Buffer = JSON.stringify(serializedObj);
		log(`updateResource(${path}) > sending payload: ${payload}`, "debug");
		payload = Buffer.from(payload);

		await coap.request(
			`${this.requestBase}${path}`, "put", payload,
		);
		return true;
	}
github AlCalzone / node-tradfri-client / src / tradfri-client.ts View on Github external
payload?: object,
	): Promise<{
		code: string,
		payload: any,
	}> {

		// create actual payload
		let jsonPayload: string | Buffer;
		if (payload != null) {
			jsonPayload = JSON.stringify(payload);
			log("sending custom payload: " + jsonPayload, "debug");
			jsonPayload = Buffer.from(jsonPayload);
		}

		// wait for the CoAP response and respond to the message
		const resp = await coap.request(
			`${this.requestBase}${path}`,
			method,
			jsonPayload as Buffer,
		);
		return {
			code: resp.code.toString(),
			payload: parsePayload(resp),
		};
	}
}
github AlCalzone / node-tradfri-client / src / tradfri-client.ts View on Github external
public async authenticate(securityCode: string): Promise<{identity: string, psk: string}> {
		// first, check try to connect with the security code
		log("authenticate() > trying to connect with the security code", "debug");
		if (!await this.tryToConnect("Client_identity", securityCode)) {
			// that didn't work, so the code is wrong
			throw new TradfriError("The security code is wrong", TradfriErrorCodes.ConnectionFailed);
		}
		// generate a new identity
		const identity = `tradfri_${Date.now()}`;
		log(`authenticating with identity "${identity}"`, "debug");

		// request creation of new PSK
		let payload: string | Buffer = JSON.stringify({ 9090: identity });
		payload = Buffer.from(payload);
		const response = await coap.request(
			`${this.requestBase}${coapEndpoints.authentication}`,
			"post",
			payload,
		);

		// check the response
		if (response.code.toString() !== "2.01") {
			// that didn't work, so the code is wrong
			throw new TradfriError(
				`unexpected response (${response.code.toString()}) to getPSK().`,
				TradfriErrorCodes.AuthenticationFailed,
			);
		}
		// the response is a buffer containing a JSON object as a string
		const pskResponse = JSON.parse(response.payload.toString("utf8"));
		const psk = pskResponse["9091"];
github AlCalzone / node-tradfri-client / build / tradfri-client.js View on Github external
return __awaiter(this, void 0, void 0, function* () {
            // create actual payload
            let jsonPayload;
            if (payload != null) {
                jsonPayload = JSON.stringify(payload);
                logger_1.log("sending custom payload: " + jsonPayload, "debug");
                jsonPayload = Buffer.from(jsonPayload);
            }
            // wait for the CoAP response and respond to the message
            const resp = yield this.swallowInternalCoapRejections(node_coap_client_1.CoapClient.request(`${this.requestBase}${path}`, method, jsonPayload));
            return {
                code: resp.code.toString(),
                payload: parsePayload(resp),
            };
        });
    }
github AlCalzone / node-tradfri-client / build / tradfri-client.js View on Github external
return __awaiter(this, void 0, void 0, function* () {
            // check if we are already observing this resource
            const observerUrl = this.getObserverUrl(path);
            if (this.observedPaths.indexOf(observerUrl) > -1)
                return false;
            // start observing
            this.observedPaths.push(observerUrl);
            // and remember the callback to restore it after a soft-reset
            this.rememberedObserveCallbacks.set(observerUrl, callback);
            yield this.swallowInternalCoapRejections(node_coap_client_1.CoapClient.observe(observerUrl, "get", callback));
            return true;
        });
    }
github AlCalzone / node-tradfri-client / build / tradfri-client.js View on Github external
return __awaiter(this, void 0, void 0, function* () {
            // initialize CoAP client
            node_coap_client_1.CoapClient.reset();
            node_coap_client_1.CoapClient.setSecurityParams(this.hostname, {
                psk: { [identity]: psk },
            });
            logger_1.log(`Attempting connection. Identity = ${identity}, psk = ${psk}`, "debug");
            const result = yield node_coap_client_1.CoapClient.tryToConnect(this.requestBase);
            if (result === true) {
                logger_1.log("Connection successful", "debug");
            }
            else {
                logger_1.log("Connection failed. Reason: " + result, "debug");
            }
            return result;
        });
    }
github AlCalzone / node-tradfri-client / build / tradfri-client.js View on Github external
return __awaiter(this, void 0, void 0, function* () {
            // initialize CoAP client
            node_coap_client_1.CoapClient.reset();
            node_coap_client_1.CoapClient.setSecurityParams(this.hostname, {
                psk: { [identity]: psk },
            });
            logger_1.log(`Attempting connection. Identity = ${identity}, psk = ${psk}`, "debug");
            const result = yield node_coap_client_1.CoapClient.tryToConnect(this.requestBase);
            if (result === true) {
                logger_1.log("Connection successful", "debug");
            }
            else {
                logger_1.log("Connection failed. Reason: " + result, "debug");
            }
            return result;
        });
    }
github eclipse / thingweb.node-wot / packages / binding-coap / src / coaps-client.ts View on Github external
* information regarding copyright ownership.
 * 
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0, or the W3C Software Notice and
 * Document License (2015-05-13) which is available at
 * https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document.
 * 
 * SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
 ********************************************************************************/

/**
 * CoAPS client based on node-coap-client by AlCalzone
 */

const coaps = require("node-coap-client").CoapClient;
import * as url from "url";
import * as TD from "@node-wot/td-tools";

import { Subscription } from 'rxjs/Subscription';

import { ProtocolClient, Content } from "@node-wot/core";
import { CoapForm } from "./coap";

export default class CoapsClient implements ProtocolClient {

  // FIXME coap Agent closes socket when no messages in flight -> new socket with every request
  private authorization: any;

  constructor() {
    // Intentionally blank
  }