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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ thing.setPropertyWriteHandler('on', async function (value) {
});
```

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:

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

### Actions

Set action handlers:
Expand Down
3 changes: 2 additions & 1 deletion examples/lamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const partialTD = {
type: 'boolean',
title: 'On/Off',
description: 'Whether the lamp is turned on',
observable: true,
},
level: {
type: 'number',
Expand All @@ -21,13 +22,13 @@ const partialTD = {
unit: 'percent',
minimum: 0,
maximum: 100,
observable: true,
},
},
actions: {
fade: {
title: 'Fade',
description: 'Fade the lamp to a given level',
synchronous: false,
input: {
type: 'object',
properties: {
Expand Down
57 changes: 51 additions & 6 deletions src/property-affordance.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ class PropertyAffordance extends InteractionAffordance {
enum;

/**
* @type {boolean|undefined}
* @type {boolean}
*/
readOnly;
readOnly = false;

/**
* @type {boolean|undefined}
* @type {boolean}
*/
writeOnly;
writeOnly = false;

/**
* @type {string|undefined}
Expand All @@ -61,9 +61,9 @@ class PropertyAffordance extends InteractionAffordance {
/* End of property data schema */

/**
* @type {boolean|undefined}
* @type {boolean}
*/
observeable;
observable = false;

/**
* @type {DataSchema}
Expand Down Expand Up @@ -97,6 +97,13 @@ class PropertyAffordance extends InteractionAffordance {
validationError.merge(error);
}

// Parse observable member
try {
this.#parseObservableMember(metadata.observable);
} catch (error) {
validationError.merge(error);
}

// Check that readOnly and writeOnly are not both set
if (this.readOnly && this.writeOnly) {
let readWriteError = new ValidationError([
Expand Down Expand Up @@ -176,6 +183,30 @@ class PropertyAffordance extends InteractionAffordance {
}
}

/**
* Parse observable member.
*
* @param {boolean|undefined} observable
*/
#parseObservableMember(observable) {
if (!(observable === undefined || typeof observable == 'boolean')) {
throw new ValidationError([
{
field: `properties.${this.name}.observable`,
description: 'observable member is not a boolean',
},
]);
}

// If undefined then default to false
if (observable === undefined) {
this.observable = false;
// Otherwise set the provided value
} else {
this.observable = observable;
}
}

/**
* Parse type member.
*
Expand Down Expand Up @@ -308,6 +339,11 @@ class PropertyAffordance extends InteractionAffordance {
metadata.writeOnly = true;
}

// Only set observable member if explicitly set to true since false is default
if (this.observable === true) {
metadata.observable = true;
}

// Generate Form
const propertyForm = {
href: `properties/${this.name}`,
Expand All @@ -321,6 +357,15 @@ class PropertyAffordance extends InteractionAffordance {
}
metadata.forms.push(propertyForm);

if (this.writeOnly !== true && this.observable === true) {
metadata.forms.push({
href: `properties/${this.name}`,
op: ['observeproperty', 'unobserveproperty'],
contentType: 'application/json',
subprotocol: 'sse',
});
}

return metadata;
}
}
Expand Down
49 changes: 48 additions & 1 deletion src/thing-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class ThingServer {
this.app.get(
'/properties/:name',
/**
* Read Property
* Read or Observe Property
*
* @param {Request} request
* @param {Response} response
Expand All @@ -44,6 +44,53 @@ class ThingServer {
const name = Array.isArray(request.params.name)
? request.params.name[0]
: request.params.name;

const requestedEventStream =
request.accepts('text/event-stream') &&
!request.accepts('application/json');

if (requestedEventStream) {
const property = this.thing.properties.get(name);
if (!property) {
response.status(404).send();
return;
} else if (
property.writeOnly === true ||
property.observable !== true
) {
response.status(406).send();
return;
}

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

/**
* @param {string} changedName The name of the Property that changed.
* @param {any} value The new value of the changed Property.
* @param {string} eventId Event ID in date-time format.
*/
const onPropertyChanged = (changedName, value, eventId) => {
if (changedName !== name || response.writableEnded) {
return;
}
response.write(
`event: ${name}\ndata: ${JSON.stringify(value)}\nid: ${eventId}\n\n`,
);
};

this.thing.on('propertyChanged', onPropertyChanged);
response.on('close', () => {
this.thing.off('propertyChanged', onPropertyChanged);
});
response.flushHeaders();
return;
}

let value;
try {
value = await this.thing.readProperty(name);
Expand Down
49 changes: 47 additions & 2 deletions src/thing.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ValidationError from './validation-error.js';
import PropertyAffordance from './property-affordance.js';
import ActionAffordance from './action-affordance.js';
import { EventEmitter } from 'node:events';
/** @import {SecurityScheme, PartialPropertyDescription, PropertyDescription,
* PartialActionDescription, ActionDescription, PartialThingDescription,
* ThingDescription, ActionStatus} from "./types.js"
Expand All @@ -14,7 +15,7 @@ import ActionAffordance from './action-affordance.js';
* Implements a Thing from the W3C WoT Thing Description 1.1 specification.
* https://www.w3.org/TR/wot-thing-description/#thing
*/
class Thing {
class Thing extends EventEmitter {
DEFAULT_CONTEXT = 'https://www.w3.org/2022/wot/td/v1.1';

/**
Expand All @@ -37,6 +38,8 @@ class Thing {
*/
actions = new Map();

#lastPropertyChangeTimestamp = 0;

/**
* @type {Record<string, SecurityScheme>}
*/
Expand All @@ -59,6 +62,8 @@ class Thing {
* to which Forms will be added.
*/
constructor(partialTD) {
super();

// Create an empty validation error to collect errors during parsing.
let validationError = new ValidationError([]);

Expand Down Expand Up @@ -442,7 +447,47 @@ class Thing {
console.error(`No property called ${name} could be found`);
throw new Error('NotFoundError');
}
return property.write(value);
const result = await property.write(value);
if (property.observable === true && property.writeOnly !== true) {
await this.emitPropertyChange(name, value);
}
return result;
}

/**
* Emit a property change to observers.
*
* @param {string} name The name of the property that changed.
* @param {any} [value] The new property value. If omitted, it is read from the property handler.
* @returns {Promise<void>} A Promise that resolves once the change has been emitted.
*/
async emitPropertyChange(name, value) {
const property = this.properties.get(name);
if (!property) {
console.error(`No property called ${name} could be found`);
throw new Error('NotFoundError');
}
if (property.writeOnly === true || property.observable !== true) {
console.error(
'Tried to emit a property change for a non-observable or write-only property',
);
throw new Error('InternalError');
}
const data = value === undefined ? await property.read() : value;
if (!property.valueSchema.validate(data)) {
console.error('Tried to emit a property change with an invalid value');
throw new Error('InternalError');
}
this.#lastPropertyChangeTimestamp = Math.max(
Date.now(),
this.#lastPropertyChangeTimestamp + 1,
);
this.emit(
'propertyChanged',
name,
data,
new Date(this.#lastPropertyChangeTimestamp).toISOString(),
);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
*
* @typedef {InteractionDescription & DataSchemaDescription & {
* forms: Array<Form>,
* observeable?: boolean|undefined
* observable?: boolean|undefined
* }} PropertyDescription
*/

Expand All @@ -95,7 +95,7 @@
*
* @typedef {InteractionDescription & DataSchemaDescription & {
* forms?: Array<Form>,
* observeable?: boolean|undefined
* observable?: boolean|undefined
* }} PartialPropertyDescription
*/

Expand Down
41 changes: 41 additions & 0 deletions test/property-affordance.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ describe('PropertyAffordance', () => {

assert.equal(property.readOnly, false);
assert.equal(property.writeOnly, false);
assert.equal(property.observable, false);
assert.equal(property.type, 'string');
assert.ok(property.valueSchema instanceof DataSchema);
});
Expand Down Expand Up @@ -64,6 +65,22 @@ describe('PropertyAffordance', () => {
return true;
},
);

assert.throws(
() => new PropertyAffordance('badObservable', { observable: 'yes' }),
(error) => {
assert.ok(error instanceof ValidationError);
assert.equal(
error.validationErrors[0].field,
'properties.badObservable.observable',
);
assert.equal(
error.validationErrors[0].description,
'observable member is not a boolean',
);
return true;
},
);
});

it('should reject properties that are both readOnly and writeOnly', () => {
Expand Down Expand Up @@ -106,6 +123,30 @@ describe('PropertyAffordance', () => {
});
});

it('should generate observe forms only for observable properties', () => {
const property = new PropertyAffordance('brightness', {
type: 'number',
observable: true,
});

assert.deepEqual(property.getMetadata(), {
type: 'number',
observable: true,
forms: [
{
href: 'properties/brightness',
op: ['readproperty', 'writeproperty'],
},
{
href: 'properties/brightness',
op: ['observeproperty', 'unobserveproperty'],
contentType: 'application/json',
subprotocol: 'sse',
},
],
});
});

it('should generate read-only form operations for readOnly properties', () => {
const property = new PropertyAffordance('temperature', {
type: 'number',
Expand Down
Loading
Loading