/
single-thing.js
120 lines (106 loc) · 2.85 KB
/
single-thing.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// -*- mode: js; js-indent-level:2; -*-
// SPDX-License-Identifier: MPL-2.0
const {
Action,
Event,
Property,
SingleThing,
Thing,
Value,
WebThingServer,
} = require('webthing');
const uuidv4 = require('uuid/v4');
class OverheatedEvent extends Event {
constructor(thing, data) {
super(thing, 'overheated', data);
}
}
class FadeAction extends Action {
constructor(thing, input) {
super(uuidv4(), thing, 'fade', input);
}
performAction() {
return new Promise((resolve) => {
setTimeout(() => {
this.thing.setProperty('brightness', this.input.brightness);
this.thing.addEvent(new OverheatedEvent(this.thing, 102));
resolve();
}, this.input.duration);
});
}
}
function makeThing() {
const thing = new Thing('urn:dev:ops:my-lamp-1234',
'My Lamp',
['OnOffSwitch', 'Light'],
'A web connected lamp');
thing.addProperty(
new Property(thing,
'on',
new Value(true),
{
'@type': 'OnOffProperty',
title: 'On/Off',
type: 'boolean',
description: 'Whether the lamp is turned on',
}));
thing.addProperty(
new Property(thing,
'brightness',
new Value(50),
{
'@type': 'BrightnessProperty',
title: 'Brightness',
type: 'integer',
description: 'The level of light from 0-100',
minimum: 0,
maximum: 100,
unit: 'percent',
}));
thing.addAvailableAction(
'fade',
{
title: 'Fade',
description: 'Fade the lamp to a given level',
input: {
type: 'object',
required: [
'brightness',
'duration',
],
properties: {
brightness: {
type: 'integer',
minimum: 0,
maximum: 100,
unit: 'percent',
},
duration: {
type: 'integer',
minimum: 1,
unit: 'milliseconds',
},
},
},
},
FadeAction);
thing.addAvailableEvent(
'overheated',
{
description: 'The lamp has exceeded its safe operating temperature',
type: 'number',
unit: 'degree celsius',
});
return thing;
}
function runServer() {
const thing = makeThing();
// If adding more than one thing, use MultipleThings() with a name.
// In the single thing case, the thing's name will be broadcast.
const server = new WebThingServer(new SingleThing(thing), 8888);
process.on('SIGINT', () => {
server.stop().then(() => process.exit()).catch(() => process.exit());
});
server.start().catch(console.error);
}
runServer();