forked from eclipse-thingweb/node-wot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoap-server.ts
613 lines (578 loc) · 29.8 KB
/
coap-server.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/********************************************************************************
* Copyright (c) 2018 - 2021 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
********************************************************************************/
/**
* CoAP Server based on coap by mcollina
*/
import * as url from "url";
import * as TD from "@node-wot/td-tools";
import Servient, { ProtocolServer, ContentSerdes, ExposedThing, Helpers, ProtocolHelpers } from "@node-wot/core";
const coap = require("coap");
export default class CoapServer implements ProtocolServer {
public readonly scheme: string = "coap";
private readonly PROPERTY_DIR = "properties";
private readonly ACTION_DIR = "actions";
private readonly EVENT_DIR = "events";
private readonly port: number = 5683;
private readonly address: string = undefined;
private readonly server: any = coap.createServer((req: any, res: any) => {
this.handleRequest(req, res);
});
private readonly things: Map<string, ExposedThing> = new Map<string, ExposedThing>();
private servient: Servient = null;
constructor(port?: number, address?: string) {
if (port !== undefined) {
this.port = port;
}
if (address !== undefined) {
this.address = address;
}
// WoT-specific content formats
coap.registerFormat(ContentSerdes.JSON_LD, 2100);
// TODO also register content fromat with IANA
// from experimental range for now
coap.registerFormat(ContentSerdes.TD, 65100);
// TODO need hook from ContentSerdes for runtime data formats
}
public start(servient: Servient): Promise<void> {
console.info(
"[binding-coap]",
`CoapServer starting on ${this.address !== undefined ? this.address + " " : ""}port ${this.port}`
);
return new Promise<void>((resolve, reject) => {
// store servient to get credentials
this.servient = servient;
// start promise handles all errors until successful start
this.server.once("error", (err: Error) => {
reject(err);
});
this.server.listen(this.port, this.address, () => {
// once started, console "handles" errors
this.server.on("error", (err: Error) => {
console.error("[binding-coap]", `CoapServer for port ${this.port} failed: ${err.message}`);
});
resolve();
});
});
}
public stop(): Promise<void> {
console.info("[binding-coap]", `CoapServer stopping on port ${this.getPort()}`);
return new Promise<void>((resolve, reject) => {
// stop promise handles all errors from now on
this.server.once("error", (err: Error) => {
reject(err);
});
this.server.close(() => {
resolve();
});
});
}
/** returns socket to be re-used by CoapClients */
public getSocket(): any {
return this.server._sock;
}
/** returns server port number and indicates that server is running when larger than -1 */
public getPort(): number {
if (this.server._sock) {
return this.server._sock.address().port;
} else {
return -1;
}
}
public expose(thing: ExposedThing, tdTemplate?: WoT.ExposedThingInit): Promise<void> {
const slugify = require("slugify");
let urlPath = slugify(thing.title, { lower: true });
if (this.things.has(urlPath)) {
urlPath = Helpers.generateUniqueName(urlPath);
}
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} exposes '${thing.title}' as unique '/${urlPath}'`
);
if (this.getPort() !== -1) {
this.things.set(urlPath, thing);
// fill in binding data
for (const address of Helpers.getAddresses()) {
for (const type of ContentSerdes.get().getOfferedMediaTypes()) {
const base: string =
this.scheme + "://" + address + ":" + this.getPort() + "/" + encodeURIComponent(urlPath);
for (const propertyName in thing.properties) {
const href = base + "/" + this.PROPERTY_DIR + "/" + encodeURIComponent(propertyName);
const form = new TD.Form(href, type);
ProtocolHelpers.updatePropertyFormWithTemplate(form, tdTemplate, propertyName);
if (thing.properties[propertyName].readOnly) {
form.op = ["readproperty"];
} else if (thing.properties[propertyName].writeOnly) {
form.op = ["writeproperty"];
} else {
form.op = ["readproperty", "writeproperty"];
}
if (thing.properties[propertyName].observable) {
if (!form.op) {
form.op = [];
}
form.op.push("observeproperty");
form.op.push("unobserveproperty");
}
thing.properties[propertyName].forms.push(form);
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} assigns '${href}' to Property '${propertyName}'`
);
}
for (const actionName in thing.actions) {
const href = base + "/" + this.ACTION_DIR + "/" + encodeURIComponent(actionName);
const form = new TD.Form(href, type);
ProtocolHelpers.updateActionFormWithTemplate(form, tdTemplate, actionName);
form.op = "invokeaction";
thing.actions[actionName].forms.push(form);
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} assigns '${href}' to Action '${actionName}'`
);
}
for (const eventName in thing.events) {
const href = base + "/" + this.EVENT_DIR + "/" + encodeURIComponent(eventName);
const form = new TD.Form(href, type);
ProtocolHelpers.updateEventFormWithTemplate(form, tdTemplate, eventName);
form.op = ["subscribeevent", "unsubscribeevent"];
thing.events[eventName].forms.push(form);
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} assigns '${href}' to Event '${eventName}'`
);
}
} // media types
} // addresses
} // running
return new Promise<void>((resolve, reject) => {
resolve();
});
}
public destroy(thingId: string): Promise<boolean> {
console.debug("[binding-coap]", `CoapServer on port ${this.getPort()} destroying thingId '${thingId}'`);
return new Promise<boolean>((resolve, reject) => {
let removedThing: ExposedThing;
for (const name of Array.from(this.things.keys())) {
const expThing = this.things.get(name);
if (expThing?.id === thingId) {
this.things.delete(name);
removedThing = expThing;
}
}
if (removedThing) {
console.info("[binding-coap]", `CoapServer succesfully destroyed '${removedThing.title}'`);
} else {
console.info("[binding-coap]", `CoapServer failed to destroy thing with thingId '${thingId}'`);
}
resolve(removedThing != undefined);
});
}
private handleRequest(req: any, res: any) {
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} received '${req.method}(${req._packet.messageId}) ${
req.url
}' from ${Helpers.toUriLiteral(req.rsinfo.address)}:${req.rsinfo.port}`
);
res.on("finish", () => {
console.debug(
"[binding-coap]",
`CoapServer replied with '${res.code}' to ${Helpers.toUriLiteral(req.rsinfo.address)}:${
req.rsinfo.port
}`
);
});
const requestUri = url.parse(req.url);
let contentType = req.options["Content-Format"];
if (req.method === "PUT" || req.method === "POST") {
if (!contentType && req.payload) {
console.warn(
"[binding-coap]",
`CoapServer on port ${this.getPort()} received no Content-Format from ${Helpers.toUriLiteral(
req.rsinfo.address
)}:${req.rsinfo.port}`
);
contentType = ContentSerdes.DEFAULT;
} else if (
ContentSerdes.get().getSupportedMediaTypes().indexOf(ContentSerdes.getMediaType(contentType)) < 0
) {
res.code = "4.15";
res.end("Unsupported Media Type");
return;
}
}
// route request
const segments = decodeURI(requestUri.pathname).split("/");
if (segments[1] === "") {
// no path -> list all Things
if (req.method === "GET") {
res.setHeader("Content-Type", ContentSerdes.DEFAULT);
res.code = "2.05";
const list = [];
for (const address of Helpers.getAddresses()) {
// FIXME are Iterables really such a non-feature that I need array?
for (const name of Array.from(this.things.keys())) {
list.push(
this.scheme +
"://" +
Helpers.toUriLiteral(address) +
":" +
this.getPort() +
"/" +
encodeURIComponent(name)
);
}
}
res.end(JSON.stringify(list));
} else {
res.code = "4.05";
res.end("Method Not Allowed");
}
// resource found and response sent
return;
} else {
// path -> select Thing
const thing = this.things.get(segments[1]);
if (thing) {
if (segments.length === 2 || segments[2] === "") {
// Thing root -> send TD
if (req.method === "GET") {
res.setOption("Content-Format", ContentSerdes.TD);
res.code = "2.05";
res.end(JSON.stringify(thing.getThingDescription()));
} else {
res.code = "4.05";
res.end("Method Not Allowed");
}
// resource found and response sent
return;
} else if (segments[2] === this.PROPERTY_DIR) {
// sub-path -> select Property
const property = thing.properties[segments[3]];
if (property) {
if (req.method === "GET") {
// readproperty
if (req.headers.Observe === undefined) {
thing
.readProperty(segments[3])
// property.read()
.then((value) => {
const contentType = ProtocolHelpers.getPropertyContentType(
thing.getThingDescription(),
segments[3],
"coap"
);
const content = ContentSerdes.get().valueToContent(
value,
<any>property,
contentType
);
res.setOption("Content-Format", content.type);
res.code = "2.05";
res.end(content.body);
})
.catch((err) => {
console.error(
"[binding-coap]",
`CoapServer on port ${this.getPort()} got internal error on read '${
requestUri.pathname
}': ${err.message}`
);
res.code = "5.00";
res.end(err.message);
});
// observeproperty
} else {
var oInterval = setInterval(function () {
thing
.readProperty(segments[3])
// property.read() periodically
.then((value) => {
const contentType = ProtocolHelpers.getPropertyContentType(
thing.getThingDescription(),
segments[3],
"coap"
);
const content = ContentSerdes.get().valueToContent(
value,
<any>property,
contentType
);
res.setOption("Content-Format", content.type);
res.code = "2.05";
res.write(content.body);
res.on("finish", function (err: Error) {
clearInterval(oInterval);
res.end();
});
})
.catch((err) => {
console.error(
"[binding-coap]",
`CoapServer on port ${this.getPort()} got internal error on read '${
requestUri.pathname
}': ${err.message}`
);
res.code = "5.00";
res.end(err.message);
});
}, 100);
}
// writeproperty
} else if (req.method === "PUT") {
if (!property.readOnly) {
let value;
try {
value = ContentSerdes.get().contentToValue(
{ type: contentType, body: req.payload },
<any>property
);
} catch (err) {
console.warn(
"[binding-coap]",
`CoapServer on port ${this.getPort()} cannot process write data for Property '${
segments[3]
}: ${err.message}'`
);
res.code = "4.00";
res.end("Invalid Data");
return;
}
thing
.writeProperty(segments[3], value)
// property.write(value)
.then(() => {
res.code = "2.04";
res.end("Changed");
})
.catch((err) => {
console.error(
"[binding-coap]",
`CoapServer on port ${this.getPort()} got internal error on write '${
requestUri.pathname
}': ${err.message}`
);
res.code = "5.00";
res.end(err.message);
});
} else {
res.code = "4.00";
res.end("Property readOnly");
}
} else {
res.code = "4.05";
res.end("Method Not Allowed");
}
// resource found and response sent
return;
} // Property exists?
} else if (segments[2] === this.ACTION_DIR) {
// sub-path -> select Action
const action = thing.actions[segments[3]];
if (action) {
// invokeaction
if (req.method === "POST") {
let input;
try {
input = ContentSerdes.get().contentToValue(
{ type: contentType, body: req.payload },
action.input
);
} catch (err) {
console.warn(
"[binding-coap]",
`CoapServer on port ${this.getPort()} cannot process input to Action '${
segments[3]
}: ${err.message}'`
);
res.code = "4.00";
res.end("Invalid Input Data");
return;
}
thing
.invokeAction(segments[3], input)
// action.invoke(input)
.then((output) => {
if (output) {
const contentType = ProtocolHelpers.getActionContentType(
thing.getThingDescription(),
segments[3],
"coap"
);
const content = ContentSerdes.get().valueToContent(
output,
action.output,
contentType
);
res.setOption("Content-Format", content.type);
res.code = "2.05";
res.end(content.body);
} else {
res.code = "2.04";
res.end();
}
})
.catch((err) => {
console.error(
"[binding-coap]",
`CoapServer on port ${this.getPort()} got internal error on invoke '${
requestUri.pathname
}': ${err.message}`
);
res.code = "5.00";
res.end(err.message);
});
} else {
res.code = "4.05";
res.end("Method Not Allowed");
}
// resource found and response sent
return;
} // Action exists?
} else if (segments[2] === this.EVENT_DIR) {
// sub-path -> select Event
const event = thing.events[segments[3]];
if (event) {
// subscribeevent
if (req.method === "GET") {
if (req.headers.Observe === 0) {
// work-around to avoid duplicate requests (resend due to no response)
// (node-coap does not deduplicate when Observe is set)
const packet = res._packet;
packet.code = "0.00";
packet.payload = "";
packet.reset = false;
packet.ack = true;
packet.token = new Buffer(0);
res._send(res, packet);
res._packet.confirmable = res._request.confirmable;
res._packet.token = res._request.token;
// end of work-around
const subscription = thing
.subscribeEvent(
segments[3],
// let subscription = event.subscribe(
(data) => {
let content;
try {
const contentType = ProtocolHelpers.getEventContentType(
thing.getThingDescription(),
segments[3],
"coap"
);
content = ContentSerdes.get().valueToContent(
data,
event.data,
contentType
);
} catch (err) {
console.warn(
"[binding-coap]",
`CoapServer on port ${this.getPort()} cannot process data for Event '${
segments[3]
}: ${err.message}'`
);
res.code = "5.00";
res.end("Invalid Event Data");
return;
}
// send event data
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} sends '${
segments[3]
}' notification to ${Helpers.toUriLiteral(req.rsinfo.address)}:${
req.rsinfo.port
}`
);
res.setOption("Content-Format", content.type);
res.code = "2.05";
res.write(content.body);
}
// ,
// () => {
// console.log(`CoapServer on port ${this.getPort()} failed '${segments[3]}' subscription`);
// res.code = "5.00";
// res.end();
// },
// () => {
// console.log(`CoapServer on port ${this.getPort()} completes '${segments[3]}' subscription`);
// res.end();
// }
)
.then(() => {
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} completes '${
segments[3]
}' subscription`
);
res.end();
})
.catch(() => {
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} failed '${segments[3]}' subscription`
);
res.code = "5.00";
res.end();
});
res.on("finish", () => {
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} ends '${
segments[3]
}' observation from ${Helpers.toUriLiteral(req.rsinfo.address)}:${
req.rsinfo.port
}`
);
thing.unsubscribeEvent(segments[3]);
// subscription.unsubscribe();
});
} else if (req.headers.Observe > 0) {
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} sends '${
segments[3]
}' response to ${Helpers.toUriLiteral(req.rsinfo.address)}:${req.rsinfo.port}`
);
// node-coap does not support GET cancellation
res.code = "5.01";
res.end("node-coap issue: no GET cancellation, send RST");
} else {
console.debug(
"[binding-coap]",
`CoapServer on port ${this.getPort()} rejects '${
segments[3]
}' read from ${Helpers.toUriLiteral(req.rsinfo.address)}:${req.rsinfo.port}`
);
res.code = "4.00";
res.end("No Observe Option");
}
} else {
res.code = "4.05";
res.end("Method Not Allowed");
}
// resource found and response sent
return;
} // Event exists?
}
} // Thing exists?
}
// resource not found
res.code = "4.04";
res.end("Not Found");
}
}