-
Notifications
You must be signed in to change notification settings - Fork 80
/
smart-coffee-machine.js
395 lines (395 loc) · 17.2 KB
/
smart-coffee-machine.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/********************************************************************************
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* 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
********************************************************************************/
// This is an example of Web of Things producer ("server" mode) Thing script.
// 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.
let allAvailableResources;
let possibleDrinks;
let maintenanceNeeded;
let schedules;
let servedCounter;
function readFromSensor(sensorType) {
// Actual implementation of reading data from a sensor can go here
// For the sake of example, let's just return a value
return 100;
}
function notify(subscribers, msg) {
// Actual implementation of notifying subscribers with a message can go here
console.log(msg);
}
WoT.produce({
title: "Smart-Coffee-Machine",
description: `A smart coffee machine with a range of capabilities.
A complementary tutorial is available at http://www.thingweb.io/smart-coffee-machine.html.`,
support: "https://github.com/eclipse-thingweb/node-wot/",
properties: {
allAvailableResources: {
type: "object",
description: `Current level of all available resources given as an integer percentage for each particular resource.
The data is obtained from the machine's sensors but can be set manually via the availableResourceLevel property in case the sensors are broken.`,
readOnly: true,
properties: {
water: {
type: "integer",
minimum: 0,
maximum: 100,
},
milk: {
type: "integer",
minimum: 0,
maximum: 100,
},
chocolate: {
type: "integer",
minimum: 0,
maximum: 100,
},
coffeeBeans: {
type: "integer",
minimum: 0,
maximum: 100,
},
},
},
availableResourceLevel: {
type: "number",
description: `Current level of a particular resource. Requires resource id variable as uriVariables.
The property can also be overridden, which also requires resource id as uriVariables.`,
uriVariables: {
id: {
type: "string",
enum: ["water", "milk", "chocolate", "coffeeBeans"],
},
},
},
possibleDrinks: {
type: "array",
description: `The list of possible drinks in general. Doesn't depend on the available resources.`,
readOnly: true,
items: {
type: "string",
},
},
servedCounter: {
type: "integer",
description: `The total number of served beverages.`,
minimum: 0,
},
maintenanceNeeded: {
type: "boolean",
description: `Shows whether a maintenance is needed. The property is observable. Automatically set to true when the servedCounter property exceeds 1000.`,
observable: true,
},
schedules: {
type: "array",
description: `The list of scheduled tasks.`,
readOnly: true,
items: {
type: "object",
properties: {
drinkId: {
type: "string",
description: `Defines what drink to make, drinkId is one of possibleDrinks property values, e.g. latte.`,
},
size: {
type: "string",
description: `Defines the size of a drink, s = small, m = medium, l = large.`,
enum: ["s", "m", "l"],
},
quantity: {
type: "integer",
description: `Defines how many drinks to make, ranging from 1 to 5.`,
minimum: 1,
maximum: 5,
},
time: {
type: "string",
description: `Defines the time of the scheduled task in 24h format, e.g. 10:00 or 21:00.`,
},
mode: {
type: "string",
description: `Defines the mode of the scheduled task, e.g. once or everyday. All the possible values are given in the enum field of this Thing Description.`,
enum: [
"once",
"everyday",
"everyMo",
"everyTu",
"everyWe",
"everyTh",
"everyFr",
"everySat",
"everySun",
],
},
},
},
},
},
actions: {
makeDrink: {
description: `Make a drink from available list of beverages. Accepts drink id, size and quantity as uriVariables.
Brews one medium americano if no uriVariables are specified.`,
uriVariables: {
drinkId: {
type: "string",
description: `Defines what drink to make, drinkId is one of possibleDrinks property values, e.g. latte.`,
},
size: {
type: "string",
description: `Defines the size of a drink, s = small, m = medium, l = large.`,
enum: ["s", "m", "l"],
},
quantity: {
type: "integer",
description: `Defines how many drinks to make, ranging from 1 to 5.`,
minimum: 1,
maximum: 5,
},
},
output: {
type: "object",
description: `Returns true/false and a message when all invoked promises are resolved (asynchronous).`,
properties: {
result: {
type: "boolean",
},
message: {
type: "string",
},
},
},
},
setSchedule: {
description: `Add a scheduled task to the schedules property. Accepts drink id, size, quantity, time and mode as body of a request.
Assumes one medium americano if not specified, but time and mode are mandatory fields.`,
input: {
type: "object",
properties: {
drinkId: {
type: "string",
description: `Defines what drink to make, drinkId is one of possibleDrinks property values, e.g. latte.`,
},
size: {
type: "string",
description: `Defines the size of a drink, s = small, m = medium, l = large.`,
enum: ["s", "m", "l"],
},
quantity: {
type: "integer",
description: `Defines how many drinks to make, ranging from 1 to 5.`,
minimum: 1,
maximum: 5,
},
time: {
type: "string",
description: `Defines the time of the scheduled task in 24h format, e.g. 10:00 or 21:00.`,
},
mode: {
type: "string",
description: `Defines the mode of the scheduled task, e.g. once or everyday. All the possible values are given in the enum field of this Thing Description.`,
enum: [
"once",
"everyday",
"everyMo",
"everyTu",
"everyWe",
"everyTh",
"everyFr",
"everySat",
"everySun",
],
},
},
required: ["time", "mode"],
},
output: {
type: "object",
description: `Returns true/false and a message when all invoked promises are resolved (asynchronous).`,
properties: {
result: {
type: "boolean",
},
message: {
type: "string",
},
},
},
},
},
events: {
outOfResource: {
description: `Out of resource event. Emitted when the available resource level is not sufficient for a desired drink.`,
data: {
type: "string",
},
},
},
})
.then((thing) => {
// Initialize the property values
allAvailableResources = {
water: readFromSensor("water"),
milk: readFromSensor("milk"),
chocolate: readFromSensor("chocolate"),
coffeeBeans: readFromSensor("coffeeBeans"),
};
possibleDrinks = ["espresso", "americano", "cappuccino", "latte", "hotChocolate", "hotWater"];
maintenanceNeeded = false;
schedules = [];
thing.setPropertyReadHandler("allAvailableResources", async () => allAvailableResources);
thing.setPropertyReadHandler("possibleDrinks", async () => possibleDrinks);
thing.setPropertyReadHandler("maintenanceNeeded", async () => maintenanceNeeded);
thing.setPropertyReadHandler("schedules", async () => schedules);
// Override a write handler for servedCounter property,
// raising maintenanceNeeded flag when the value exceeds 1000 drinks
thing.setPropertyWriteHandler("servedCounter", async (val) => {
servedCounter = await val.value();
if (servedCounter > 1000) {
maintenanceNeeded = true;
thing.emitPropertyChange("maintenanceNeeded");
// Notify a "maintainer" when the value has changed
// (the notify function here simply logs a message to the console)
notify(
`maintenanceNeeded property has changed, new value is: ${maintenanceNeeded}`
);
}
});
// Now initialize the servedCounter property
servedCounter = readFromSensor("servedCounter");
// Override a write handler for availableResourceLevel property,
// utilizing the uriVariables properly
thing.setPropertyWriteHandler("availableResourceLevel", async (val, options) => {
// Check if uriVariables are provided
if (options && typeof options === "object" && "uriVariables" in options) {
const uriVariables = options.uriVariables;
if ("id" in uriVariables) {
const id = uriVariables.id;
allAvailableResources[id] = await val.value();
return;
}
}
throw Error("Please specify id variable as uriVariables.");
});
// Override a read handler for availableResourceLevel property,
// utilizing the uriVariables properly
thing.setPropertyReadHandler("availableResourceLevel", async (options) => {
// Check if uriVariables are provided
if (options && typeof options === "object" && "uriVariables" in options) {
const uriVariables = options.uriVariables;
if ("id" in uriVariables) {
const id = uriVariables.id;
return allAvailableResources[id];
}
}
throw Error("Please specify id variable as uriVariables.");
});
// Set up a handler for makeDrink action
thing.setActionHandler("makeDrink", async (_params, options) => {
// Default values
let drinkId = "americano";
let size = "m";
let quantity = 1;
// Size quantifiers
const sizeQuantifiers = { s: 0.1, m: 0.2, l: 0.3 };
// Drink recipes showing the amount of a resource consumed for a particular drink
const drinkRecipes = {
espresso: {
water: 1,
milk: 0,
chocolate: 0,
coffeeBeans: 2,
},
americano: {
water: 2,
milk: 0,
chocolate: 0,
coffeeBeans: 2,
},
cappuccino: {
water: 1,
milk: 1,
chocolate: 0,
coffeeBeans: 2,
},
latte: {
water: 1,
milk: 2,
chocolate: 0,
coffeeBeans: 2,
},
hotChocolate: {
water: 0,
milk: 0,
chocolate: 1,
coffeeBeans: 0,
},
hotWater: {
water: 1,
milk: 0,
chocolate: 0,
coffeeBeans: 0,
},
};
// Check if uriVariables are provided
if (options && typeof options === "object" && "uriVariables" in options) {
const uriVariables = options.uriVariables;
drinkId = "drinkId" in uriVariables ? uriVariables.drinkId : drinkId;
size = "size" in uriVariables ? uriVariables.size : size;
quantity = "quantity" in uriVariables ? uriVariables.quantity : quantity;
}
// Calculate the new level of resources
const newResources = Object.assign({}, allAvailableResources);
newResources.water -= Math.ceil(quantity * sizeQuantifiers[size] * drinkRecipes[drinkId].water);
newResources.milk -= Math.ceil(quantity * sizeQuantifiers[size] * drinkRecipes[drinkId].milk);
newResources.chocolate -= Math.ceil(quantity * sizeQuantifiers[size] * drinkRecipes[drinkId].chocolate);
newResources.coffeeBeans -= Math.ceil(quantity * sizeQuantifiers[size] * drinkRecipes[drinkId].coffeeBeans);
// Check if the amount of available resources is sufficient to make a drink
for (const resource in newResources) {
if (newResources[resource] <= 0) {
thing.emitEvent("outOfResource", `Low level of ${resource}: ${newResources[resource]}%`);
return { result: false, message: `${resource} level is not sufficient` };
}
}
// Now store the new level of allAvailableResources
allAvailableResources = newResources;
servedCounter = servedCounter + quantity;
// Finally deliver the drink
return { result: true, message: `Your ${drinkId} is in progress!` };
});
// Set up a handler for setSchedule action
thing.setActionHandler("setSchedule", async (params, options) => {
const paramsp = await params.value(); // : any = await Helpers.parseInteractionOutput(params);
// Check if uriVariables are provided
if (paramsp != null && typeof paramsp === "object" && "time" in paramsp && "mode" in paramsp) {
// Use default values if not provided
paramsp.drinkId = "drinkId" in paramsp ? paramsp.drinkId : "americano";
paramsp.size = "size" in paramsp ? paramsp.size : "m";
paramsp.quantity = "quantity" in paramsp ? paramsp.quantity : 1;
// Now add a new schedule
schedules.push(paramsp);
return { result: true, message: `Your schedule has been set!` };
}
return { result: false, message: `Please provide all the required parameters: time and mode.` };
});
// Finally expose the thing
thing.expose().then(() => {
console.info(`${thing.getThingDescription().title} ready`);
});
console.log(`Produced ${thing.getThingDescription().title}`);
})
.catch((e) => {
console.log(e);
});