This repository has been archived by the owner on Dec 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathws-thing.js
130 lines (115 loc) · 3.04 KB
/
ws-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
121
122
123
124
125
126
127
128
129
130
import { Thing, Property, Value, Action } from "webthing";
import { v4 as uuid } from "uuid";
const SENSOR_UNIT = {
AmbientLightSensor: 'lux',
ProximitySensor: 'cm',
Gyroscope: 'rad/s',
Accelerometer: 'm/s²'
};
class NotifyAction extends Action {
/**
*
* @param {WebSocketThing} thing
* @param {string} input
*/
constructor(thing, input) {
super(uuid(), thing, 'notify', input);
}
performAction() {
this.thing.send({
type: 'notify',
message: this.input
});
return super.performAction();
}
}
class VibrateAction extends Action {
/**
*
* @param {WebSocketThing} thing
* @param {number} input
*/
constructor(thing, input) {
super(uuid(), thing, 'vibrate', input);
}
performAction() {
this.thing.send({
type: 'vibrate',
time: this.input
});
return super.performAction();
}
}
export default class WebSocketThing extends Thing {
constructor(websocket, spec) {
super(spec.id || uuid(), spec.name, [], 'A web browser');
this.ws = websocket;
this.setUiHref('/static');
this.setHrefPrefix(`/${this.id}`);
for(const sensor of spec.sensors) {
this.addSensor(sensor);
}
this.addProperty(new Property(this, 'visible', new Value(!spec.hidden), {
readOnly: true,
type: 'boolean',
title: 'Page visible'
}));
if(spec.can.notify) {
this.addAvailableAction('notify', {
title: 'Notify',
input: {
type: 'string'
}
}, NotifyAction);
}
if(spec.can.vibrate) {
this.addAvailableAction('vibrate', {
title: 'Vibrate',
input: {
type: 'integer',
minimum: 0,
default: 10
}
}, VibrateAction);
}
}
/**
* Called when the thing was made available in the server.
* @param {string} host - Host the thing is available at.
*/
registered(host) {
this.send({
type: 'created',
url: `http://${host}/${this.id}`,
id: this.id
});
}
addSensor(sensor) {
const desc = {
readOnly: true,
type: 'number',
title: sensor.type,
unit: SENSOR_UNIT[sensor.type]
};
this.addProperty(new Property(this, sensor.type, new Value(sensor.value), desc));
}
updateSensor(sensor) {
const property = this.findProperty(sensor.type);
if(property) {
property.value.notifyOfExternalUpdate(sensor.value);
}
}
/**
*
* @param {boolean} hidden
*/
updateVisibility(hidden) {
this.findProperty('visible').value.notifyOfExternalUpdate(!hidden);
}
/**
* @param {any} msg
*/
send(msg) {
this.ws.send(JSON.stringify(msg));
}
}