Skip to content

Commit

Permalink
add missing files...
Browse files Browse the repository at this point in the history
  • Loading branch information
danielpeintner committed Aug 2, 2023
1 parent d0ff86f commit 8784743
Show file tree
Hide file tree
Showing 9 changed files with 113 additions and 60 deletions.
16 changes: 10 additions & 6 deletions examples/scripts/countdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ WoT.produce({
const listToDelete = [];
for (const id of countdowns.keys()) {
const as = countdowns.get(id);
if (as.output !== undefined) {
if (as !== undefined && as.output !== undefined) {
const prev = as.output;
as.output--;
console.log("\t" + id + ", from " + prev + " to " + as.output);
Expand Down Expand Up @@ -125,18 +125,22 @@ WoT.produce({
};
const ii = resp;
console.log("init countdown value = " + JSON.stringify(resp));
countdowns.set(resp.href, resp);
countdowns.set(resp.href !== undefined ? resp.href : "", resp);
return ii;
});
thing.setActionHandler("stopCountdown", async (params, options) => {
if (params) {
const value = await params.value();
if (typeof value === "string" && countdowns.has(value)) {
const as = countdowns.get(value);
as.output = 0;
as.status = Status.completed;
console.log("Countdown stopped for href: " + value);
return undefined;
if (as !== undefined) {
as.output = 0;
as.status = Status.completed;
console.log("Countdown stopped for href: " + value);
return null;
} else {
throw Error("Countdown value is undefined for href, " + value);
}
} else {
throw Error("Input provided for stopCountdown is no string or invalid href, " + value);
}
Expand Down
7 changes: 3 additions & 4 deletions packages/core/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import * as TDT from "wot-thing-description-types";
import { ContentSerdes } from "./content-serdes";
import Ajv, { ValidateFunction, ErrorObject } from "ajv";
import TDSchema from "wot-thing-description-types/schema/td-json-schema-validation.json";
import { DataSchemaValue, ExposedThingInit } from "wot-typescript-definitions";
import { DataSchemaValue, ExposedThingInit, ThingDescription } from "wot-typescript-definitions";
import { SomeJSONSchema } from "ajv/dist/types/json-schema";
import { ThingInteraction, ThingModelHelpers } from "@node-wot/td-tools";
import { Resolver } from "@node-wot/td-tools/src/resolver-interface";
Expand Down Expand Up @@ -152,9 +152,8 @@ export default class Helpers implements Resolver {
}
}

// TODO: specialize fetch to retrieve just thing descriptions
public fetch(uri: string): Promise<unknown> {
return new Promise<unknown>((resolve, reject) => {
public fetch(uri: string): Promise<ThingDescription> {
return new Promise<ThingDescription>((resolve, reject) => {
const client = this.srv.getClientFor(Helpers.extractScheme(uri));
debug(`WoTImpl fetching TD from '${uri}' with ${client}`);
client
Expand Down
45 changes: 22 additions & 23 deletions packages/examples/src/scripts/countdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
********************************************************************************/

import { InteractionOptions } from "wot-typescript-definitions";

function uuidv4(): string {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
Expand Down Expand Up @@ -91,8 +89,8 @@ WoT.produce({
console.log("Update countdowns");
const listToDelete: string[] = [];
for (const id of countdowns.keys()) {
const as: ActionStatus = countdowns.get(id);
if (as.output !== undefined) {
const as = countdowns.get(id);
if (as !== undefined && as.output !== undefined) {
const prev = as.output;
as.output--;
console.log("\t" + id + ", from " + prev + " to " + as.output);
Expand All @@ -117,20 +115,17 @@ WoT.produce({
}, 1000);

// set property handlers (using async-await)
thing.setPropertyReadHandler(
"countdowns",
async (options: InteractionOptions): Promise<WoT.InteractionInput> => {
const cts: string[] = [];
for (const id of countdowns.keys()) {
cts.push(id);
}
return cts;
thing.setPropertyReadHandler("countdowns", async (options): Promise<WoT.InteractionInput> => {
const cts: string[] = [];
for (const id of countdowns.keys()) {
cts.push(id);
}
);
return cts;
});
// set action handlers (using async-await)
thing.setActionHandler(
"startCountdown",
async (params: WoT.InteractionOutput, options: InteractionOptions): Promise<WoT.InteractionInput> => {
async (params: WoT.InteractionOutput, options): Promise<WoT.InteractionInput> => {
let initValue = 100;
if (params) {
const value = await params.value();
Expand All @@ -145,21 +140,25 @@ WoT.produce({
};
const ii: WoT.InteractionInput = resp;
console.log("init countdown value = " + JSON.stringify(resp));
countdowns.set(resp.href, resp);
countdowns.set(resp.href !== undefined ? resp.href : "", resp);
return ii;
}
);
thing.setActionHandler(
"stopCountdown",
async (params: WoT.InteractionOutput, options: InteractionOptions): Promise<WoT.InteractionInput> => {
async (params: WoT.InteractionOutput, options): Promise<WoT.InteractionInput> => {
if (params) {
const value = await params.value();
if (typeof value === "string" && countdowns.has(value)) {
const as: ActionStatus = countdowns.get(value);
as.output = 0;
as.status = Status.completed;
console.log("Countdown stopped for href: " + value);
return undefined;
const as = countdowns.get(value);
if (as !== undefined) {
as.output = 0;
as.status = Status.completed;
console.log("Countdown stopped for href: " + value);
return null;
} else {
throw Error("Countdown value is undefined for href, " + value);
}
} else {
throw Error("Input provided for stopCountdown is no string or invalid href, " + value);
}
Expand All @@ -170,11 +169,11 @@ WoT.produce({
);
thing.setActionHandler(
"monitorCountdown",
async (params: WoT.InteractionOutput, options: InteractionOptions): Promise<WoT.InteractionInput> => {
async (params: WoT.InteractionOutput, options): Promise<WoT.InteractionInput> => {
if (params) {
const value = await params.value();
if (typeof value === "string" && countdowns.has(value)) {
const as: ActionStatus = countdowns.get(value);
const as = countdowns.get(value);
return JSON.stringify(as);
} else {
throw Error("Input provided for monitorCountdown is no string or invalid href, " + value);
Expand Down
24 changes: 17 additions & 7 deletions packages/examples/src/scripts/counter-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,33 @@
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
********************************************************************************/

import { Helpers } from "@node-wot/core";
import { Servient, Helpers } from "@node-wot/core";
import { HttpClientFactory } from "@node-wot/binding-http";
import { CoapClientFactory } from "@node-wot/binding-coap";
import { ThingDescription } from "wot-typescript-definitions";

let WoTHelpers: Helpers;
// create Servient and add HTTP/CoAP binding
const servient = new Servient();
servient.addClientFactory(new HttpClientFactory());
servient.addClientFactory(new CoapClientFactory());

const wotHelper = new Helpers(servient);

function getFormIndexForDecrementWithCoAP(thing: WoT.ConsumedThing): number {
const forms = thing.getThingDescription().actions.decrement.forms;
for (let i = 0; i < forms.length; i++) {
if (/^coaps?:\/\/.*/.test(forms[i].href)) {
return i;
const forms = thing.getThingDescription().actions?.decrement.forms;
if (forms !== undefined) {
for (let i = 0; i < forms.length; i++) {
if (/^coaps?:\/\/.*/.test(forms[i].href)) {
return i;
}
}
}
// return formIndex: 0 if no CoAP target IRI found
return 0;
}

WoTHelpers.fetch("coap://localhost:5683/counter")
wotHelper
.fetch("coap://localhost:5683/counter")
.then(async (td) => {
// using await for serial execution (note 'async' in then() of fetch())
try {
Expand Down
6 changes: 3 additions & 3 deletions packages/examples/src/scripts/counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ WoT.produce({
let fill = "black";
if (options && typeof options === "object" && "uriVariables" in options) {
console.log("options = " + JSON.stringify(options));
if ("fill" in options.uriVariables) {
if (options.uriVariables && "fill" in options.uriVariables) {
const uriVariables = options.uriVariables as Record<string, string>;
fill = uriVariables.fill;
}
Expand All @@ -234,7 +234,7 @@ WoT.produce({
let step = 1;
if (options && typeof options === "object" && "uriVariables" in options) {
console.log("options = " + JSON.stringify(options));
if ("step" in options.uriVariables) {
if (options.uriVariables && "step" in options.uriVariables) {
const uriVariables = options.uriVariables as Record<string, unknown>;
step = uriVariables.step as number;
}
Expand All @@ -251,7 +251,7 @@ WoT.produce({
let step = 1;
if (options && typeof options === "object" && "uriVariables" in options) {
console.log("options = " + JSON.stringify(options));
if ("step" in options.uriVariables) {
if (options.uriVariables && "step" in options.uriVariables) {
const uriVariables = options.uriVariables as Record<string, unknown>;
step = uriVariables.step as number;
}
Expand Down
18 changes: 13 additions & 5 deletions packages/examples/src/scripts/smart-coffee-machine-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,17 @@
// It considers a fictional smart coffee machine in order to demonstrate the capabilities of Web of Things.
// An accompanying tutorial is available at http://www.thingweb.io/smart-coffee-machine.html.

import { Servient, Helpers } from "@node-wot/core";
import { HttpClientFactory } from "@node-wot/binding-http";
import { CoapClientFactory } from "@node-wot/binding-coap";
import { ThingDescription } from "wot-typescript-definitions";
import { Helpers } from "@node-wot/core";
let WoTHelpers: Helpers;

// create Servient and add HTTP/CoAP binding
const servient = new Servient();
servient.addClientFactory(new HttpClientFactory());
servient.addClientFactory(new CoapClientFactory());

const wotHelper = new Helpers(servient);

// Print data and an accompanying message in a distinguishable way
function log(msg: string, data: unknown) {
Expand All @@ -29,7 +37,7 @@ function log(msg: string, data: unknown) {
console.info("======================");
}

WoTHelpers.fetch("http://127.0.0.1:8080/smart-coffee-machine").then(async (td) => {
wotHelper.fetch("http://127.0.0.1:8080/smart-coffee-machine").then(async (td) => {
try {
const thing = await WoT.consume(td as ThingDescription);
log("Thing Description:", td);
Expand Down Expand Up @@ -60,7 +68,7 @@ WoTHelpers.fetch("http://127.0.0.1:8080/smart-coffee-machine").then(async (td) =
const makeCoffee = await thing.invokeAction("makeDrink", undefined, {
uriVariables: { drinkId: "latte", size: "l", quantity: 3 },
});
const makeCoffeep = (await makeCoffee.value()) as Record<string, unknown>;
const makeCoffeep = (await makeCoffee?.value()) as Record<string, unknown>;
if (makeCoffeep.result) {
log("Enjoy your drink!", makeCoffeep);
} else {
Expand All @@ -79,7 +87,7 @@ WoTHelpers.fetch("http://127.0.0.1:8080/smart-coffee-machine").then(async (td) =
time: "10:00",
mode: "everyday",
});
const scheduledTaskp = (await scheduledTask.value()) as Record<string, string>;
const scheduledTaskp = (await scheduledTask?.value()) as Record<string, string>;
log(scheduledTaskp.message, scheduledTaskp);

// See how it has been added to the schedules property
Expand Down
17 changes: 13 additions & 4 deletions packages/examples/src/security/oauth/consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,24 @@
*
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
********************************************************************************/
import { Helpers } from "@node-wot/core";

import { Servient, Helpers } from "@node-wot/core";
import { HttpClientFactory } from "@node-wot/binding-http";
import { CoapClientFactory } from "@node-wot/binding-coap";
import { ThingDescription } from "wot-typescript-definitions";

let WoTHelpers: Helpers;
// create Servient and add HTTP/CoAP binding
const servient = new Servient();
servient.addClientFactory(new HttpClientFactory());
servient.addClientFactory(new CoapClientFactory());

const wotHelper = new Helpers(servient);

WoTHelpers.fetch("https://localhost:8080/oauth").then((td) => {
wotHelper.fetch("https://localhost:8080/oauth").then((td) => {
WoT.consume(td as ThingDescription).then(async (thing) => {
try {
const result = await (await thing.invokeAction("sayOk")).value();
const resp = await thing.invokeAction("sayOk");
const result = resp?.value();
console.log("oAuth token was", result);
} catch (error) {
console.log("It seems that I couldn't access the resource");
Expand Down
36 changes: 30 additions & 6 deletions packages/examples/src/testthing/testclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,17 @@
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
********************************************************************************/

import { Helpers } from "@node-wot/core";
import { Servient, Helpers } from "@node-wot/core";
import { HttpClientFactory } from "@node-wot/binding-http";
import { CoapClientFactory } from "@node-wot/binding-coap";
import { ThingDescription } from "wot-typescript-definitions";
let WoTHelpers: Helpers;

// create Servient and add HTTP/CoAP binding
const servient = new Servient();
servient.addClientFactory(new HttpClientFactory());
servient.addClientFactory(new CoapClientFactory());

const wotHelper = new Helpers(servient);

console.log = () => {
/* empty */
Expand All @@ -30,7 +38,11 @@ async function testPropertyRead(thing: WoT.ConsumedThing, name: string) {
const value = await res.value();
console.info("PASS " + name + " READ:", value);
} catch (err) {
console.error("FAIL " + name + " READ:", err.message);
if (err instanceof Error) {
console.error("FAIL " + name + " READ:", err.message);
} else {
console.error("FAIL " + name + " READ:", err);
}
}
}

Expand All @@ -46,12 +58,24 @@ async function testPropertyWrite(
if (!shouldFail) console.info("PASS " + name + " WRITE (" + displayValue + ")");
else console.error("FAIL " + name + " WRITE: (" + displayValue + ")");
} catch (err) {
if (!shouldFail) console.error("FAIL " + name + " WRITE (" + displayValue + "):", err.message);
else console.info("PASS " + name + " WRITE (" + displayValue + "):", err.message);
if (!shouldFail) {
if (err instanceof Error) {
console.error("FAIL " + name + " WRITE (" + displayValue + "):", err.message);
} else {
console.error("FAIL " + name + " WRITE (" + displayValue + "):", err);
}
} else {
if (err instanceof Error) {
console.info("PASS " + name + " WRITE (" + displayValue + "):", err.message);
} else {
console.info("PASS " + name + " WRITE (" + displayValue + "):", err);
}
}
}
}

WoTHelpers.fetch("http://localhost:8080/testthing")
wotHelper
.fetch("http://localhost:8080/testthing")
.then(async (td) => {
// using await for serial execution (note 'async' in then() of fetch())
try {
Expand Down
4 changes: 2 additions & 2 deletions packages/examples/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"strict": true,
"strictFunctionTypes": true,
"outDir": "dist",
"rootDir": "src",
"target": "ES2018",
"alwaysStrict": false,
"noImplicitUseStrict": true,
"sourceMap": false,
"removeComments": false
},
Expand Down

0 comments on commit 8784743

Please sign in to comment.