-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientClass.ts
79 lines (65 loc) · 2.63 KB
/
clientClass.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import {Servient} from '@node-wot/core';
import {HttpServer, HttpClientFactory, HttpsClientFactory} from '@node-wot/binding-http'
import {Helpers} from '@node-wot/core';
// add delay function
function delay(ms: number) {
return new Promise( resolve => setTimeout(resolve, ms) );
}
export class makeWoTinteraction{
// variable
TDfile:string;
client:Servient;
wotHelper:Helpers;
data:WoT.DataSchemaValue;
// constructor
constructor(fileAddress:string,credentials?:any){
this.TDfile = fileAddress; // local path or remote ip address
// init WoT server
// create Servient and add HTTP binding
this.client = new Servient();
this.client.addClientFactory(new HttpsClientFactory());
this.client.addClientFactory(new HttpClientFactory());
this.wotHelper = new Helpers(this.client);
// if need credential to access the server
this.client.addCredentials(credentials);
this.data = "null";
}
async invokeAction(actionName:string, options?:any) {
this.wotHelper
.fetch(this.TDfile)
.then(async (td: any) => {
// using await for serial execution (note 'async' in then() of fetch())
const WoT = await this.client.start();
const thing = await WoT.consume(td);
//console.log(options);
await thing.invokeAction(actionName, options);
console.log("invoke action " + actionName);
})
.catch((err) => {
console.error("invoke action error:", err);
});
}
async readProperty(propertyName:string):Promise<WoT.DataSchemaValue>{
let td:any = await this.wotHelper.fetch(this.TDfile);
// using await for serial execution (note 'async' in then() of fetch())
const WoT = await this.client.start();
const thing = await WoT.consume(td);
let data:WoT.DataSchemaValue;
data = (await (await thing.readProperty(propertyName)).value());
return data;
}
async writeProperty(propertyName:string,options:any){
this.wotHelper
.fetch(this.TDfile)
.then(async (td: any) => {
// using await for serial execution (note 'async' in then() of fetch())
const WoT = await this.client.start();
const thing = await WoT.consume(td);
await thing.writeProperty(propertyName,options);
})
.catch((err) => {
console.error("write property error:", err);
});
}
}
export {};