Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ const thing = new Thing(partialTD);

### Properties

Set property handlers:
Set property read and write handlers for each property defined in the Thing Description:

```javascript
thing.setPropertyReadHandler('on', async function () {
Expand All @@ -97,21 +97,27 @@ thing.setPropertyReadHandler('level', async function () {
});

thing.setPropertyWriteHandler('on', async function (value) {
// Update the lamp state.
// Update the lamp on/off state.
});

thing.setPropertyWriteHandler('level', async function (value) {
// Update the lamp level.
});
```

Property changes are emitted automatically when an observable property is written via its write handler, but for other property changes you should explicitly call `emitPropertyChange()` to notify active SSE observers. You can provide the new value directly, or
omit it to read the current value using the property's read handler:
Property changes are emitted automatically when an observable property is written via its write handler, but for other property changes you should explicitly call `emitPropertyChange()` to notify active SSE observers:

```javascript
await thing.emitPropertyChange('on', true);

If the value argument is omitted then the current value is read using the read handler and that value is emitted.

await thing.emitPropertyChange('on');
```

### Actions

Set action handlers:
Set action invoke handlers for each action defined in the Thing Description:

```javascript
thing.setActionInvokeHandler('fade', async (input, signal) => {
Expand All @@ -123,12 +129,18 @@ For synchronous actions set `synchronous` to `true` in the Thing Description. Th

For asynchronous actions set `synchronous` to `false` in the Thing Description. The invoke handler should accept the action input as its first argument, and an optional `AbortSignal` as a second argument so the action can be stopped if the request is cancelled.

### Thing Server
### Events

Expose to the Thing to the Web of Things by starting its web server, providing
a port number as an argument:
Call `emitEvent()` whenever an event occurs for one of the
event affordances defined in the Thing Description:

```javascript
thing.emitEvent('overheated', 90);
```

### Thing Server

Create and start a Thing server using your Thing.
Expose to the Thing to the Web of Things by instantiating a Thing server for the Thing, then calling start() to start its web server (providing a port number as an argument):

```javascript
const server = new ThingServer(thing);
Expand Down
4 changes: 2 additions & 2 deletions src/action-affordance.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class ActionAffordance extends InteractionAffordance {
outputSchema;

/**
* Create a new Action.
* Create a new Action Affordance.
*
* @param {string} name The name of the ActionAffordance from its
* key in an actions Map.
Expand Down Expand Up @@ -409,7 +409,7 @@ class ActionAffordance extends InteractionAffordance {
/** @type {Array<Form>} */
metadata.forms = [];
const invokeActionForm = {
href: `actions/${this.name}`,
href: `actions/${encodeURIComponent(this.name)}`,
op: 'invokeaction',
};
metadata.forms.push(invokeActionForm);
Expand Down
81 changes: 81 additions & 0 deletions src/event-affordance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import InteractionAffordance from './interaction-affordance.js';
import ValidationError from './validation-error.js';
import DataSchema from './data-schema.js';

/** @import {DataSchemaDescription, EventDescription, PartialEventDescription} from "./types.js" */

/**
* Event Affordance
*
* Represents an EventAffordance from the W3C WoT Thing Description 1.1
* specification https://www.w3.org/TR/wot-thing-description/#eventaffordance
*/
class EventAffordance extends InteractionAffordance {
/**
* Raw data schema description.
*
* @type {DataSchemaDescription|undefined}
*/
data;

/**
* Parsed data schema used for validation.
*
* @type {DataSchema}
*/
dataSchema;

/**
* Create a new Event Affordance.
*
* @param {string} name The name of the EventAffordance from its key in an
* events Map.
* @param {PartialEventDescription} metadata Metadata describing an
* EventAffordance from a partial Thing Description.
*/
constructor(name, metadata) {
super(name, metadata);

// Parse data member
this.#parseDataMember(metadata.data);
this.dataSchema = new DataSchema(this.data, `events.${this.name}.data`);
}

/**
* Parse data member.
*
* @param {DataSchemaDescription|undefined} data
*/
#parseDataMember(data) {
if (!(data === undefined || typeof data === 'object')) {
throw new ValidationError([
{
field: `events.${this.name}.data`,
description: 'data member is not valid',
},
]);
}
this.data = data;
}

/**
* @returns {EventDescription}
*/
getMetadata() {
const metadata = /** @type {EventDescription} */ (super.getMetadata());
if (this.data !== undefined) {
metadata.data = this.data;
}
metadata.forms = [
{
href: `events/${encodeURIComponent(this.name)}`,
op: ['subscribeevent', 'unsubscribeevent'],
contentType: 'application/json',
subprotocol: 'sse',
},
];
return metadata;
}
}

export default EventAffordance;
4 changes: 2 additions & 2 deletions src/property-affordance.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ class PropertyAffordance extends InteractionAffordance {
valueSchema;

/**
* Create a new Property.
* Create a new Property Affordance.
*
* @param {string} name The name of the PropertyAffordance from its
* key in a properties Map.
Expand Down Expand Up @@ -359,7 +359,7 @@ class PropertyAffordance extends InteractionAffordance {

if (this.writeOnly !== true && this.observable === true) {
metadata.forms.push({
href: `properties/${this.name}`,
href: `properties/${encodeURIComponent(this.name)}`,
op: ['observeproperty', 'unobserveproperty'],
contentType: 'application/json',
subprotocol: 'sse',
Expand Down
50 changes: 50 additions & 0 deletions src/thing-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,56 @@ class ThingServer {
},
);

this.app.get(
'/events/:name',
/**
* Subscribe to an Event
*
* @param {Request} request
* @param {Response} response
*/
(request, response) => {
const name = Array.isArray(request.params.name)
? request.params.name[0]
: request.params.name;
if (!this.thing.events.has(name)) {
response.status(404).send();
return;
}
if (!request.accepts('text/event-stream')) {
response.status(406).send();
return;
}

response.status(200);
response.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});

/**
* @param {string} eventName The name of the Event that occurred.
* @param {any} data The event data.
* @param {string} eventId Event ID in date-time format.
*/
const onEventEmitted = (eventName, data, eventId) => {
if (eventName !== name || response.writableEnded) {
return;
}
const dataLine =
data === undefined ? '' : `data: ${JSON.stringify(data)}\n`;
response.write(`event: ${name}\n${dataLine}id: ${eventId}\n\n`);
};

this.thing.on('eventEmitted', onEventEmitted);
response.on('close', () => {
this.thing.off('eventEmitted', onEventEmitted);
});
response.flushHeaders();
},
);

this.app.put(
'/properties',
/**
Expand Down
99 changes: 98 additions & 1 deletion src/thing.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import ValidationError from './validation-error.js';
import PropertyAffordance from './property-affordance.js';
import ActionAffordance from './action-affordance.js';
import EventAffordance from './event-affordance.js';
import { EventEmitter } from 'node:events';
/** @import {SecurityScheme, PartialPropertyDescription, PropertyDescription,
* PartialActionDescription, ActionDescription, PartialThingDescription,
* ThingDescription, ActionStatus} from "./types.js"
* PartialEventDescription, EventDescription, ThingDescription, ActionStatus} from "./types.js"
*/

/**
Expand Down Expand Up @@ -38,8 +39,15 @@ class Thing extends EventEmitter {
*/
actions = new Map();

/**
* @type {Map<string, EventAffordance>}
*/
events = new Map();

#lastPropertyChangeTimestamp = 0;

#lastEventTimestamp = 0;

/**
* @type {Record<string, SecurityScheme>}
*/
Expand Down Expand Up @@ -102,6 +110,13 @@ class Thing extends EventEmitter {
validationError.merge(error);
}

// Parse events member
try {
this.#parseEventsMember(partialTD.events);
} catch (error) {
validationError.merge(error);
}

// Hard code the nosec security scheme for now
this.securityDefinitions = {
nosec_sc: {
Expand Down Expand Up @@ -284,6 +299,31 @@ class Thing extends EventEmitter {
}
}

/**
* Parse the events member of a Thing Description.
*
* @param {Record<string, PartialEventDescription>|undefined} eventDescriptions Map of event
* descriptions provided in a partial TD, indexed by event name.
*/
#parseEventsMember(eventDescriptions) {
if (!eventDescriptions) {
return;
}

if (typeof eventDescriptions !== 'object') {
throw new ValidationError([
{
field: 'events',
description: 'events member is not an object',
},
]);
}

for (const eventName in eventDescriptions) {
this.addEvent(eventName, eventDescriptions[eventName]);
}
}

/**
* Add a Property.
*
Expand All @@ -308,6 +348,18 @@ class Thing extends EventEmitter {
this.actions.set(actionName, action);
}

/**
* Add an Event.
*
* @param {string} eventName The name of the event to add.
* @param {PartialEventDescription} eventDescription A partial EventAffordance
* description from a Thing Description.
*/
addEvent(eventName, eventDescription) {
const event = new EventAffordance(eventName, eventDescription);
this.events.set(eventName, event);
}

/**
* Get Thing Description.
*
Expand Down Expand Up @@ -337,6 +389,17 @@ class Thing extends EventEmitter {
}
}

/**
* @type {Record<string, EventDescription>}
*/
let events = {};
for (const eventName of this.events.keys()) {
const event = this.events.get(eventName);
if (event) {
events[eventName] = event.getMetadata();
}
}

/** @type {ThingDescription} */
const thingDescription = {
'@context': this.context,
Expand Down Expand Up @@ -385,6 +448,9 @@ class Thing extends EventEmitter {
op: 'queryallactions',
});
}
if (Object.keys(events).length > 0) {
thingDescription.events = events;
}
return thingDescription;
}

Expand Down Expand Up @@ -503,6 +569,37 @@ class Thing extends EventEmitter {
);
}

/**
* Emit an Event to subscribers.
*
* @param {string} name The name of the EventAffordance that occurred.
* @param {any} [data] The event data.
* @throws {Error} Throws NotFoundError for an unknown event or InternalError
* when data does not conform to the event's data schema.
*/
emitEvent(name, data) {
const event = this.events.get(name);
if (!event) {
console.error(`No event called ${name} could be found`);
throw new Error('NotFoundError');
}
if (!event.dataSchema.validate(data)) {
console.error(`Tried to emit invalid data for event ${name}`);
throw new Error('InternalError');
}

this.#lastEventTimestamp = Math.max(
Date.now(),
this.#lastEventTimestamp + 1,
);
this.emit(
'eventEmitted',
name,
data,
new Date(this.#lastEventTimestamp).toISOString(),
);
}

/**
* Read All Properties.
*
Expand Down
Loading
Loading