registry: RangeController, ModeController, ToggleController with resources, presets and semantics

The three generic controllers are described in full and leave the stub table (62 stubs remain). A declaration
takes an instance name, friendly names from text() and asset(), and the options of the interface: range, unit and
presets for a range; supportedModes and ordered for a mode; semantics() for all three, with actions mapped to
directives and states mapped to a value or a range of values.

Refused at device.add(), each with the endpoint, interface and instance in the message: no instance name or no
friendly name; an instance declared twice; a first friendly name or a phrase used by another capability of the
endpoint; a reserved word, an asset id that is not in the catalog; range.max not above range.min; a preset off the
precision grid or outside the range; fewer than two modes or a mode listed twice; a mapping to a directive the
interface does not have, to a payload that does not fit, to a mode that is not listed, to AdjustMode on modes
that are not ordered; SetEcoOn, SetEcoOff, EcoOn and EcoOff on anything but a toggle.

For 1.x callers: Alexa.RangeController lists rangeValue (1.5.2 sent supported: []); addSupportedModes() announces
a mode given as a string as { value } and notes it, and takes { ordered: false } as a second argument, the default
stays true as 1.5.2 sent it (device.add() defaults to false). Declared the 1.x way, the zoo fan and curtain give
the same JSON as before.

Tests: the zoo blind, whose range, unit and semantics were written by hand into the JSON of 1.5.2, is declared
with device.add() and equals that JSON plus the Alexa capability; five capability objects of Amazon's examples
are reproduced the same way. 27 examples of four pages added. npm test: 108 pass (was 85) in 10.5-11.3 s, also on
Node 18.20.8 and 20.20.2.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
David 2026-09-28 15:50:25 +00:00
parent c492ef74d1
commit 2558e21787
80 changed files with 3131 additions and 107 deletions

View file

@ -28,9 +28,19 @@ class AlexaInterface extends Capability_js_1.Capability {
addFriendlyName(name, locale) { addFriendlyName(name, locale) {
this.friendlyNames.push((0, resources_js_1.text)(name, locale)); this.friendlyNames.push((0, resources_js_1.text)(name, locale));
} }
/** The modes of a ModeController, as { value, modeResources } objects. */ /**
addSupportedModes(modes) { * The modes of a ModeController, as { value, modeResources } objects. A mode given as a string is announced as
this.options.supportedModes = modes; * { value } and noted: Alexa wants friendly names for it. ordered is true unless options.ordered says otherwise,
* as 1.x announced every mode list; with device.add() the default is false.
*/
addSupportedModes(modes, options = {}) {
this.options.ordered = options.ordered ?? true;
this.options.supportedModes = modes.map((mode) => {
if (typeof mode !== "string")
return { value: mode.value, friendlyNames: (mode.modeResources?.friendlyNames ?? []) };
this.notes.push(`the mode ${mode} was given as a string, pass { value, modeResources }`);
return { value: mode, friendlyNames: [] };
});
} }
setInstance(name) { setInstance(name) {
this.instance = name; this.instance = name;

View file

@ -109,6 +109,15 @@ function checkCapability(capability, descriptor, endpoint) {
if (friendlyNames.length > 0) if (friendlyNames.length > 0)
refuse("takes no friendly names"); refuse("takes no friendly names");
} }
// A capability of device.add() passed the schema when it was declared; one declared the 1.x way did not
if (descriptor.options) {
try {
descriptor.options.parse(capability.options);
}
catch (err) {
refuse(err instanceof schema_js_1.SchemaError ? err.message : String(err));
}
}
// generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all // generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all
// controller instances for each endpoint" // controller instances for each endpoint"
const used = new Map(); const used = new Map();

25
dist/cjs/index.js vendored
View file

@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.AlexaErrorResponse = exports.AlexaErrorType = exports.ThermostatMode = exports.TemperatureSensorScale = exports.AlexaStatusMessage = exports.PowerState = exports.DisplayCategory = exports.AlexaInterfaceType = exports.AlexaActions = exports.ActionMapping = exports.AlexaInterface = exports.DisplayCategories = exports.States = exports.Actions = exports.Units = exports.Assets = exports.text = exports.asset = exports.EndpointHealth = exports.PowerController = exports.TemperatureSensor = exports.BrightnessController = exports.Alexa = exports.SchemaError = exports.DeclarationError = exports.registry = exports.Capability = exports.Device = exports.DEFAULT_HOST = exports.Alex2MQTT = void 0; exports.AlexaErrorResponse = exports.AlexaErrorType = exports.ThermostatMode = exports.TemperatureSensorScale = exports.AlexaStatusMessage = exports.PowerState = exports.DisplayCategory = exports.AlexaInterfaceType = exports.AlexaActions = exports.ActionMapping = exports.AlexaInterface = exports.DisplayCategories = exports.States = exports.Actions = exports.Units = exports.Assets = exports.SemanticsBuilder = exports.semantics = exports.text = exports.asset = exports.EndpointHealth = exports.PowerController = exports.ToggleController = exports.TemperatureSensor = exports.RangeController = exports.ModeController = exports.BrightnessController = exports.Alexa = exports.SchemaError = exports.DeclarationError = exports.registry = exports.Capability = exports.Device = exports.DEFAULT_HOST = exports.Alex2MQTT = void 0;
// Relative specifiers carry ".js": Node's ES module loader resolves no extension, and TypeScript maps it back to the .ts. // Relative specifiers carry ".js": Node's ES module loader resolves no extension, and TypeScript maps it back to the .ts.
var Alex2Node_js_1 = require("./Alex2Node.js"); var Alex2Node_js_1 = require("./Alex2Node.js");
Object.defineProperty(exports, "Alex2MQTT", { enumerable: true, get: function () { return __importDefault(Alex2Node_js_1).default; } }); Object.defineProperty(exports, "Alex2MQTT", { enumerable: true, get: function () { return __importDefault(Alex2Node_js_1).default; } });
@ -20,20 +20,25 @@ Object.defineProperty(exports, "SchemaError", { enumerable: true, get: function
var index_js_2 = require("./registry/index.js"); var index_js_2 = require("./registry/index.js");
Object.defineProperty(exports, "Alexa", { enumerable: true, get: function () { return index_js_2.Alexa; } }); Object.defineProperty(exports, "Alexa", { enumerable: true, get: function () { return index_js_2.Alexa; } });
Object.defineProperty(exports, "BrightnessController", { enumerable: true, get: function () { return index_js_2.BrightnessController; } }); Object.defineProperty(exports, "BrightnessController", { enumerable: true, get: function () { return index_js_2.BrightnessController; } });
Object.defineProperty(exports, "ModeController", { enumerable: true, get: function () { return index_js_2.ModeController; } });
Object.defineProperty(exports, "RangeController", { enumerable: true, get: function () { return index_js_2.RangeController; } });
Object.defineProperty(exports, "TemperatureSensor", { enumerable: true, get: function () { return index_js_2.TemperatureSensor; } }); Object.defineProperty(exports, "TemperatureSensor", { enumerable: true, get: function () { return index_js_2.TemperatureSensor; } });
Object.defineProperty(exports, "ToggleController", { enumerable: true, get: function () { return index_js_2.ToggleController; } });
var enums_js_1 = require("./compat/enums.js"); var enums_js_1 = require("./compat/enums.js");
Object.defineProperty(exports, "PowerController", { enumerable: true, get: function () { return enums_js_1.PowerController; } }); Object.defineProperty(exports, "PowerController", { enumerable: true, get: function () { return enums_js_1.PowerController; } });
Object.defineProperty(exports, "EndpointHealth", { enumerable: true, get: function () { return enums_js_1.EndpointHealth; } }); Object.defineProperty(exports, "EndpointHealth", { enumerable: true, get: function () { return enums_js_1.EndpointHealth; } });
var resources_js_1 = require("./registry/resources.js");
Object.defineProperty(exports, "asset", { enumerable: true, get: function () { return resources_js_1.asset; } });
Object.defineProperty(exports, "text", { enumerable: true, get: function () { return resources_js_1.text; } });
// The vocabularies of the Smart Home API
var index_js_3 = require("./registry/index.js"); var index_js_3 = require("./registry/index.js");
Object.defineProperty(exports, "Assets", { enumerable: true, get: function () { return index_js_3.ASSETS; } }); Object.defineProperty(exports, "asset", { enumerable: true, get: function () { return index_js_3.asset; } });
Object.defineProperty(exports, "Units", { enumerable: true, get: function () { return index_js_3.UNITS_OF_MEASURE; } }); Object.defineProperty(exports, "text", { enumerable: true, get: function () { return index_js_3.text; } });
Object.defineProperty(exports, "Actions", { enumerable: true, get: function () { return index_js_3.ACTIONS; } }); Object.defineProperty(exports, "semantics", { enumerable: true, get: function () { return index_js_3.semantics; } });
Object.defineProperty(exports, "States", { enumerable: true, get: function () { return index_js_3.STATES; } }); Object.defineProperty(exports, "SemanticsBuilder", { enumerable: true, get: function () { return index_js_3.SemanticsBuilder; } });
Object.defineProperty(exports, "DisplayCategories", { enumerable: true, get: function () { return index_js_3.DISPLAY_CATEGORIES; } }); // The vocabularies of the Smart Home API
var index_js_4 = require("./registry/index.js");
Object.defineProperty(exports, "Assets", { enumerable: true, get: function () { return index_js_4.ASSETS; } });
Object.defineProperty(exports, "Units", { enumerable: true, get: function () { return index_js_4.UNITS_OF_MEASURE; } });
Object.defineProperty(exports, "Actions", { enumerable: true, get: function () { return index_js_4.ACTIONS; } });
Object.defineProperty(exports, "States", { enumerable: true, get: function () { return index_js_4.STATES; } });
Object.defineProperty(exports, "DisplayCategories", { enumerable: true, get: function () { return index_js_4.DISPLAY_CATEGORIES; } });
// 1.x // 1.x
var AlexaInterface_js_1 = require("./compat/AlexaInterface.js"); var AlexaInterface_js_1 = require("./compat/AlexaInterface.js");
Object.defineProperty(exports, "AlexaInterface", { enumerable: true, get: function () { return AlexaInterface_js_1.AlexaInterface; } }); Object.defineProperty(exports, "AlexaInterface", { enumerable: true, get: function () { return AlexaInterface_js_1.AlexaInterface; } });

View file

@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaError = exports.s = exports.defineInterface = exports.DeclarationError = exports.TemperatureSensor = exports.PowerController = exports.EndpointHealth = exports.BrightnessController = exports.Alexa = exports.registry = void 0; exports.SchemaError = exports.s = exports.defineInterface = exports.DeclarationError = exports.SemanticsBuilder = exports.semantics = exports.text = exports.asset = exports.ToggleController = exports.TemperatureSensor = exports.RangeController = exports.PowerController = exports.ModeController = exports.EndpointHealth = exports.BrightnessController = exports.Alexa = exports.registry = void 0;
// The interfaces the library knows, by namespace. // The interfaces the library knows, by namespace.
const Alexa_js_1 = require("./interfaces/Alexa.js"); const Alexa_js_1 = require("./interfaces/Alexa.js");
Object.defineProperty(exports, "Alexa", { enumerable: true, get: function () { return Alexa_js_1.Alexa; } }); Object.defineProperty(exports, "Alexa", { enumerable: true, get: function () { return Alexa_js_1.Alexa; } });
@ -22,18 +22,27 @@ const BrightnessController_js_1 = require("./interfaces/BrightnessController.js"
Object.defineProperty(exports, "BrightnessController", { enumerable: true, get: function () { return BrightnessController_js_1.BrightnessController; } }); Object.defineProperty(exports, "BrightnessController", { enumerable: true, get: function () { return BrightnessController_js_1.BrightnessController; } });
const EndpointHealth_js_1 = require("./interfaces/EndpointHealth.js"); const EndpointHealth_js_1 = require("./interfaces/EndpointHealth.js");
Object.defineProperty(exports, "EndpointHealth", { enumerable: true, get: function () { return EndpointHealth_js_1.EndpointHealth; } }); Object.defineProperty(exports, "EndpointHealth", { enumerable: true, get: function () { return EndpointHealth_js_1.EndpointHealth; } });
const ModeController_js_1 = require("./interfaces/ModeController.js");
Object.defineProperty(exports, "ModeController", { enumerable: true, get: function () { return ModeController_js_1.ModeController; } });
const PowerController_js_1 = require("./interfaces/PowerController.js"); const PowerController_js_1 = require("./interfaces/PowerController.js");
Object.defineProperty(exports, "PowerController", { enumerable: true, get: function () { return PowerController_js_1.PowerController; } }); Object.defineProperty(exports, "PowerController", { enumerable: true, get: function () { return PowerController_js_1.PowerController; } });
const RangeController_js_1 = require("./interfaces/RangeController.js");
Object.defineProperty(exports, "RangeController", { enumerable: true, get: function () { return RangeController_js_1.RangeController; } });
const TemperatureSensor_js_1 = require("./interfaces/TemperatureSensor.js"); const TemperatureSensor_js_1 = require("./interfaces/TemperatureSensor.js");
Object.defineProperty(exports, "TemperatureSensor", { enumerable: true, get: function () { return TemperatureSensor_js_1.TemperatureSensor; } }); Object.defineProperty(exports, "TemperatureSensor", { enumerable: true, get: function () { return TemperatureSensor_js_1.TemperatureSensor; } });
const ToggleController_js_1 = require("./interfaces/ToggleController.js");
Object.defineProperty(exports, "ToggleController", { enumerable: true, get: function () { return ToggleController_js_1.ToggleController; } });
const stubs_js_1 = require("./interfaces/stubs.js"); const stubs_js_1 = require("./interfaces/stubs.js");
const types_js_1 = require("./types.js"); const types_js_1 = require("./types.js");
const described = [ const described = [
Alexa_js_1.Alexa, Alexa_js_1.Alexa,
BrightnessController_js_1.BrightnessController, BrightnessController_js_1.BrightnessController,
EndpointHealth_js_1.EndpointHealth, EndpointHealth_js_1.EndpointHealth,
ModeController_js_1.ModeController,
PowerController_js_1.PowerController, PowerController_js_1.PowerController,
RangeController_js_1.RangeController,
TemperatureSensor_js_1.TemperatureSensor, TemperatureSensor_js_1.TemperatureSensor,
ToggleController_js_1.ToggleController,
]; ];
const descriptors = new Map(); const descriptors = new Map();
for (const descriptor of [...described, ...stubs_js_1.STUBS]) { for (const descriptor of [...described, ...stubs_js_1.STUBS]) {
@ -59,6 +68,12 @@ exports.registry = {
return [...descriptors.values()].sort((a, b) => (a.namespace < b.namespace ? -1 : 1)); return [...descriptors.values()].sort((a, b) => (a.namespace < b.namespace ? -1 : 1));
}, },
}; };
var resources_js_1 = require("./resources.js");
Object.defineProperty(exports, "asset", { enumerable: true, get: function () { return resources_js_1.asset; } });
Object.defineProperty(exports, "text", { enumerable: true, get: function () { return resources_js_1.text; } });
var semantics_js_1 = require("./semantics.js");
Object.defineProperty(exports, "semantics", { enumerable: true, get: function () { return semantics_js_1.semantics; } });
Object.defineProperty(exports, "SemanticsBuilder", { enumerable: true, get: function () { return semantics_js_1.SemanticsBuilder; } });
var types_js_2 = require("./types.js"); var types_js_2 = require("./types.js");
Object.defineProperty(exports, "DeclarationError", { enumerable: true, get: function () { return types_js_2.DeclarationError; } }); Object.defineProperty(exports, "DeclarationError", { enumerable: true, get: function () { return types_js_2.DeclarationError; } });
Object.defineProperty(exports, "defineInterface", { enumerable: true, get: function () { return types_js_2.defineInterface; } }); Object.defineProperty(exports, "defineInterface", { enumerable: true, get: function () { return types_js_2.defineInterface; } });

View file

@ -0,0 +1,87 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModeController = void 0;
const resources_js_1 = require("../resources.js");
const schema_js_1 = require("../schema.js");
const semantics_js_1 = require("../semantics.js");
const types_js_1 = require("../types.js");
const directives = {
SetMode: { name: "SetMode", payload: schema_js_1.s.object({ mode: schema_js_1.s.string({ min: 1 }) }) },
AdjustMode: {
name: "AdjustMode",
payload: schema_js_1.s.object({ modeDelta: schema_js_1.s.optional(schema_js_1.s.number({ integer: true })) }),
// alexa-modecontroller.html, "Capabilities object": "Modes that have an order support the AdjustMode directive."
when: ({ options }) => options.ordered === true,
note: "modeDelta is the number of modes to move by, 1 when it is left out",
},
};
// A mode is declared as { value, friendlyNames }. The object of discovery and of 1.x, { value, modeResources:
// { friendlyNames } }, is taken as well.
const eitherForm = schema_js_1.s.object({
value: schema_js_1.s.string({ min: 1 }),
friendlyNames: schema_js_1.s.optional(schema_js_1.s.unknown()),
modeResources: schema_js_1.s.optional(schema_js_1.s.object({ friendlyNames: schema_js_1.s.unknown() })),
}, { unknownKeys: "reject" });
const mode = {
expects: "a mode { value, friendlyNames }",
parse(input, path = "") {
if (typeof input !== "object" || input === null)
throw (0, schema_js_1.mismatch)(path, mode.expects, input);
const { value, friendlyNames, modeResources } = eitherForm.parse(input, path);
const named = friendlyNames === undefined && modeResources ? "modeResources.friendlyNames" : "friendlyNames";
return { value, friendlyNames: resources_js_1.labels.parse(friendlyNames ?? modeResources?.friendlyNames, (0, schema_js_1.at)(path, named)) };
},
};
/**
* One of a list of values, under an instance name: the wash cycle of a washer, the position of a garage door. Amazon
* certifies a garage door only with this interface and the display category GARAGE_DOOR.
*/
exports.ModeController = (0, types_js_1.defineInterface)({
namespace: "Alexa.ModeController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-modecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
mode: { name: "mode", value: schema_js_1.s.nullable(schema_js_1.s.string({ min: 1 })), note: "null when no mode is set, as when the device is off" },
},
directives,
options: schema_js_1.s.object({
/** At least two. When the modes have an order, in increasing order. */
supportedModes: schema_js_1.s.array(mode, { min: 2 }),
/** The modes have an order, cold to hot, and the user can say "increase": Alexa sends AdjustMode. Default: false. */
ordered: schema_js_1.s.optional(schema_js_1.s.boolean()),
semantics: schema_js_1.s.optional((0, semantics_js_1.semanticsOf)({ directives, stateValue: schema_js_1.s.string({ min: 1 }) })),
}, { unknownKeys: "reject" }),
// A capability declared the 1.x way may be without modes, or have modes without names
discovery({ options: { supportedModes = [], ordered = false } }) {
if (supportedModes.length === 0)
return {};
const modes = supportedModes.map(({ value, friendlyNames = [] }) => (friendlyNames.length > 0 ? { value, modeResources: { friendlyNames } } : { value }));
return { configuration: { ordered, supportedModes: modes } };
},
validate(capability) {
const { supportedModes, ordered = false, semantics } = capability.options;
const values = supportedModes.map(({ value }) => value);
const twice = values.find((value, i) => values.indexOf(value) !== i);
if (twice !== undefined)
throw new types_js_1.DeclarationError(capability, `the mode ${twice} is listed twice`);
const isMode = (value) => values.includes(value);
for (const { directive } of semantics?.actionMappings ?? []) {
if (directive.name === "AdjustMode" && !ordered) {
throw new types_js_1.DeclarationError(capability, "an action is mapped to AdjustMode, which needs ordered: true");
}
if (directive.name === "SetMode" && !isMode(directive.payload?.mode)) {
throw new types_js_1.DeclarationError(capability, `an action is mapped to SetMode ${directive.payload?.mode}, the modes are ${values.join(", ")}`);
}
}
for (const mapping of semantics?.stateMappings ?? []) {
if (mapping["@type"] === "StatesToValue" && !isMode(mapping.value)) {
throw new types_js_1.DeclarationError(capability, `a state is mapped to ${mapping.value}, the modes are ${values.join(", ")}`);
}
}
},
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RangeController = void 0;
const catalog_js_1 = require("../catalog.js");
const resources_js_1 = require("../resources.js");
const schema_js_1 = require("../schema.js");
const semantics_js_1 = require("../semantics.js");
const types_js_1 = require("../types.js");
const directives = {
SetRangeValue: { name: "SetRangeValue", payload: schema_js_1.s.object({ rangeValue: schema_js_1.s.number() }) },
AdjustRangeValue: {
name: "AdjustRangeValue",
payload: schema_js_1.s.object({ rangeValueDelta: schema_js_1.s.number(), rangeValueDeltaDefault: schema_js_1.s.boolean() }),
note: "rangeValueDeltaDefault is true when the user named no amount; rangeValueDelta is then the precision",
},
};
// 0.1 + 0.2 is not 0.3: a value is on the grid when it is within a millionth of a step of it
function onGrid(value, origin, step) {
const steps = (value - origin) / step;
return Math.abs(steps - Math.round(steps)) < 1e-6;
}
/**
* A number in a range, under an instance name: the position of a blind, the speed of a fan. With nonControllable it
* is a reading the user can ask for, like an air quality index.
*/
exports.RangeController = (0, types_js_1.defineInterface)({
namespace: "Alexa.RangeController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-rangecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
rangeValue: { name: "rangeValue", value: schema_js_1.s.number() },
},
directives,
options: schema_js_1.s.object({
/** precision is the step of the range and what "turn up the fan speed" changes it by. */
range: schema_js_1.s.object({ min: schema_js_1.s.number(), max: schema_js_1.s.number(), precision: schema_js_1.s.number({ gt: 0 }) }, { unknownKeys: "reject" }),
unit: schema_js_1.s.optional(schema_js_1.s.oneOf(catalog_js_1.UNITS_OF_MEASURE, "a unit of measure like Alexa.Unit.Percent")),
/** Names for values: "set the fan speed to maximum". */
presets: schema_js_1.s.optional(schema_js_1.s.array(schema_js_1.s.object({ value: schema_js_1.s.number(), friendlyNames: resources_js_1.labels }, { unknownKeys: "reject" }))),
semantics: schema_js_1.s.optional((0, semantics_js_1.semanticsOf)({ directives, stateValue: schema_js_1.s.number(), ranges: true })),
}, { unknownKeys: "reject" }),
// A capability declared the 1.x way may be without a range; check() says so, discovery lists what there is
discovery({ options: { range, unit, presets } }) {
const configuration = {
...(range && { supportedRange: { minimumValue: range.min, maximumValue: range.max, precision: range.precision } }),
...(unit && { unitOfMeasure: unit }),
...(presets && { presets: presets.map(({ value, friendlyNames }) => ({ rangeValue: value, presetResources: { friendlyNames } })) }),
};
return Object.keys(configuration).length > 0 ? { configuration } : {};
},
validate(capability) {
const { range: { min, max, precision }, presets = [], semantics } = capability.options;
const inRange = (value) => value >= min && value <= max;
if (max <= min)
throw new types_js_1.DeclarationError(capability, `range.max ${max} is not above range.min ${min}`);
for (const { value } of presets) {
// alexa-rangecontroller.html, "Preset object": "minimum range value + (n x precision) where n is an integer"
if (!inRange(value) || !onGrid(value, min, precision)) {
throw new types_js_1.DeclarationError(capability, `the preset ${value} is not ${min} + n x ${precision}, up to ${max}`);
}
}
for (const { directive } of semantics?.actionMappings ?? []) {
const { rangeValue } = directive.payload ?? {};
if (directive.name === "SetRangeValue" && !inRange(rangeValue)) {
throw new types_js_1.DeclarationError(capability, `an action is mapped to SetRangeValue ${rangeValue}, the range is ${min} to ${max}`);
}
}
},
// alexa-rangecontroller.html, "SetRangeValue directive error handling": "If your error is safety related, respond
// with an Alexa.Safety.ErrorResponse"
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ToggleController = void 0;
const schema_js_1 = require("../schema.js");
const semantics_js_1 = require("../semantics.js");
const types_js_1 = require("../types.js");
const directives = {
TurnOn: { name: "TurnOn", payload: schema_js_1.s.object({}) },
TurnOff: { name: "TurnOff", payload: schema_js_1.s.object({}) },
};
/**
* Something that is on or off, under an instance name: the oscillation of a fan, the light of an oven. The one
* generic controller that Alexa hunches work with (SetEcoOn, SetEcoOff, EcoOn, EcoOff).
*/
exports.ToggleController = (0, types_js_1.defineInterface)({
namespace: "Alexa.ToggleController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-togglecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
toggleState: { name: "toggleState", value: schema_js_1.s.enum("ON", "OFF") },
},
directives,
options: schema_js_1.s.object({
semantics: schema_js_1.s.optional((0, semantics_js_1.semanticsOf)({ directives, stateValue: schema_js_1.s.enum("ON", "OFF"), hunches: true })),
}, { unknownKeys: "reject" }),
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -48,7 +48,6 @@ const TABLE = [
["Alexa.Media.PlayQueue", "1", [], "alexa-media-playqueue.html"], ["Alexa.Media.PlayQueue", "1", [], "alexa-media-playqueue.html"],
["Alexa.Media.Playback", "1", [], "alexa-media-playback.html"], ["Alexa.Media.Playback", "1", [], "alexa-media-playback.html"],
["Alexa.Media.Search", "1", [], "alexa-media-search.html"], ["Alexa.Media.Search", "1", [], "alexa-media-search.html"],
["Alexa.ModeController", "3", ["mode"], "alexa-modecontroller.html"],
["Alexa.MotionSensor", "3", [], "alexa-motionsensor.html"], ["Alexa.MotionSensor", "3", [], "alexa-motionsensor.html"],
["Alexa.PercentageController", "3", [], "alexa-percentagecontroller.html"], ["Alexa.PercentageController", "3", [], "alexa-percentagecontroller.html"],
["Alexa.PlaybackController", "3", [], "alexa-playbackcontroller.html"], ["Alexa.PlaybackController", "3", [], "alexa-playbackcontroller.html"],
@ -56,7 +55,6 @@ const TABLE = [
["Alexa.PowerLevelController", "3", [], "alexa-powerlevelcontroller.html"], ["Alexa.PowerLevelController", "3", [], "alexa-powerlevelcontroller.html"],
["Alexa.ProactiveNotificationSource", "1", [], "alexa-proactivenotificationsource.html"], ["Alexa.ProactiveNotificationSource", "1", [], "alexa-proactivenotificationsource.html"],
["Alexa.RTCSessionController", "1", [], "alexa-rtcsessioncontroller.html"], ["Alexa.RTCSessionController", "1", [], "alexa-rtcsessioncontroller.html"],
["Alexa.RangeController", "3", [], "alexa-rangecontroller.html"],
["Alexa.RecordController", "3", [], "alexa-recordcontroller.html"], ["Alexa.RecordController", "3", [], "alexa-recordcontroller.html"],
["Alexa.RemoteVideoPlayer", "1", [], "alexa-remotevideoplayer.html"], ["Alexa.RemoteVideoPlayer", "1", [], "alexa-remotevideoplayer.html"],
["Alexa.SceneController", "3", [], "alexa-scenecontroller.html"], ["Alexa.SceneController", "3", [], "alexa-scenecontroller.html"],
@ -74,13 +72,12 @@ const TABLE = [
["Alexa.ThermostatController.Schedule", "1", [], "alexa-thermostatcontroller-schedule.html"], ["Alexa.ThermostatController.Schedule", "1", [], "alexa-thermostatcontroller-schedule.html"],
// "UNKNOWN" in 1.5.2 as well; the page is titled "Interface 3" // "UNKNOWN" in 1.5.2 as well; the page is titled "Interface 3"
["Alexa.TimeHoldController", "3", [], "alexa-timeholdcontroller.html"], ["Alexa.TimeHoldController", "3", [], "alexa-timeholdcontroller.html"],
["Alexa.ToggleController", "3", ["toggleState"], "alexa-togglecontroller.html"],
["Alexa.UIController", "1", [], "alexa-uicontroller.html"], ["Alexa.UIController", "1", [], "alexa-uicontroller.html"],
["Alexa.UserPreference", "1", [], "alexa-userpreference.html"], ["Alexa.UserPreference", "1", [], "alexa-userpreference.html"],
["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"], ["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"],
["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"], ["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"],
]; ];
// What 1.5.2 added to the capability object of three of them // What 1.5.2 added to the capability object of two of them
const EXTRAS = { const EXTRAS = {
// No properties object; supportsDeactivation and proactivelyReported on the capability itself // No properties object; supportsDeactivation and proactivelyReported on the capability itself
"Alexa.SceneController": ({ proactivelyReported }) => ({ "Alexa.SceneController": ({ proactivelyReported }) => ({
@ -90,9 +87,6 @@ const EXTRAS = {
"Alexa.ThermostatController": () => ({ "Alexa.ThermostatController": () => ({
configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false }, configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false },
}), }),
"Alexa.ModeController": ({ options }) => (options.supportedModes?.length > 0
? { configuration: { ordered: true, supportedModes: options.supportedModes } }
: {}),
}; };
function kindOf(namespace) { function kindOf(namespace) {
if (namespace.endsWith("Sensor")) if (namespace.endsWith("Sensor"))

View file

@ -27,6 +27,8 @@ const reserved = catalog_js_1.RESERVED_WORDS;
exports.label = { exports.label = {
expects: "a friendly name, from text() or asset()", expects: "a friendly name, from text() or asset()",
parse(input, path = "") { parse(input, path = "") {
if (typeof input !== "object" || input === null)
throw (0, schema_js_1.mismatch)(path, exports.label.expects, input);
const { "@type": type, value } = typed.parse(input, path); const { "@type": type, value } = typed.parse(input, path);
if (type === "asset") if (type === "asset")
return { "@type": type, value: assetValue.parse(value, (0, schema_js_1.at)(path, "value")) }; return { "@type": type, value: assetValue.parse(value, (0, schema_js_1.at)(path, "value")) };

112
dist/cjs/registry/semantics.js vendored Normal file
View file

@ -0,0 +1,112 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SemanticsBuilder = void 0;
exports.semantics = semantics;
exports.semanticsOf = semanticsOf;
// Semantics of a generic controller: the phrases "open", "close", "raise", "lower" mapped to directives, and states
// like "open" and "closed" mapped to values of the property (alexa-discovery-objects.html, "Semantics object").
const catalog_js_1 = require("./catalog.js");
const schema_js_1 = require("./schema.js");
const listed = (given) => (Array.isArray(given) ? [...given] : [given]);
const withPrefix = (prefix, name) => (name.startsWith(prefix) ? name : `${prefix}${name}`);
/**
* Collects the mappings of one capability:
*
* semantics()
* .action("Close", "SetRangeValue", { rangeValue: 0 })
* .action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 })
* .state("Closed", 0)
* .stateRange("Open", 1, 100)
*
* What is collected is checked when the capability is declared, against the directives and the property of its
* interface.
*/
class SemanticsBuilder {
constructor() {
this.actionMappings = [];
this.stateMappings = [];
}
/** The phrases send the directive. payload is its payload; leave it out for a directive that has none. */
action(actions, directive, payload) {
this.actionMappings.push({
"@type": "ActionsToDirective",
actions: listed(actions).map((name) => withPrefix("Alexa.Actions.", name)),
directive: payload === undefined ? { name: directive } : { name: directive, payload },
});
return this;
}
/** The property at this value is in these states: "is the garage door open?" */
state(states, value) {
this.stateMappings.push({ "@type": "StatesToValue", states: listed(states).map((name) => withPrefix("Alexa.States.", name)), value });
return this;
}
/** The property between the two values, both included, is in these states. For an interface with a numeric property. */
stateRange(states, minimumValue, maximumValue) {
this.stateMappings.push({
"@type": "StatesToRange",
states: listed(states).map((name) => withPrefix("Alexa.States.", name)),
range: { minimumValue, maximumValue },
});
return this;
}
}
exports.SemanticsBuilder = SemanticsBuilder;
function semantics() {
return new SemanticsBuilder();
}
const isHunch = (id) => /\.(SetEcoOn|SetEcoOff|EcoOn|EcoOff)$/.test(id);
/** The schema of the semantics option of one interface. It takes a semantics() builder or the object as discovery has it. */
function semanticsOf({ directives, stateValue, ranges = false, hunches = false }) {
const allowed = (ids, what) => {
const choice = ids.filter((id) => hunches || !isHunch(id));
return schema_js_1.s.array(schema_js_1.s.oneOf(choice, `${what}: ${choice.map((id) => id.split(".")[2]).join(", ")}`), { min: 1 });
};
const names = Object.keys(directives);
const lists = schema_js_1.s.object({ actionMappings: schema_js_1.s.optional(schema_js_1.s.array(schema_js_1.s.unknown())), stateMappings: schema_js_1.s.optional(schema_js_1.s.array(schema_js_1.s.unknown())) });
const action = schema_js_1.s.object({
"@type": schema_js_1.s.literal("ActionsToDirective"),
actions: allowed(catalog_js_1.ACTIONS, "a phrase of Alexa.Actions"),
directive: schema_js_1.s.object({ name: schema_js_1.s.oneOf(names, `a directive of the interface: ${names.join(", ")}`) }),
});
const state = schema_js_1.s.object({
"@type": ranges ? schema_js_1.s.enum("StatesToValue", "StatesToRange") : schema_js_1.s.enum("StatesToValue"),
states: allowed(catalog_js_1.STATES, "a state of Alexa.States"),
});
const range = schema_js_1.s.object({ minimumValue: schema_js_1.s.number(), maximumValue: schema_js_1.s.number() }, { unknownKeys: "reject" });
function actionMapping(input, path) {
const mapping = action.parse(input, path);
const { name, payload } = mapping.directive;
// Checked as the directive will arrive; a mapping without a payload stays without one in discovery
const checked = directives[name].payload.parse(payload ?? {}, (0, schema_js_1.at)(path, "directive.payload"));
return { "@type": mapping["@type"], actions: mapping.actions, directive: payload === undefined ? { name } : { name, payload: checked } };
}
function stateMapping(input, path) {
const mapping = state.parse(input, path);
if (mapping["@type"] === "StatesToValue") {
return { "@type": mapping["@type"], states: mapping.states, value: stateValue.parse(mapping.value, (0, schema_js_1.at)(path, "value")) };
}
const { minimumValue, maximumValue } = range.parse(mapping.range, (0, schema_js_1.at)(path, "range"));
if (minimumValue > maximumValue)
throw new schema_js_1.SchemaError((0, schema_js_1.at)(path, "range"), `the minimumValue ${minimumValue} is above the maximumValue ${maximumValue}`);
return { "@type": mapping["@type"], states: mapping.states, range: { minimumValue, maximumValue } };
}
const expects = "semantics() with at least one action or state";
return {
expects,
parse(input, path = "") {
if (typeof input !== "object" || input === null)
throw (0, schema_js_1.mismatch)(path, expects, input);
const { actionMappings = [], stateMappings = [] } = lists.parse(input, path);
if (actionMappings.length + stateMappings.length === 0)
throw (0, schema_js_1.mismatch)(path, expects, {});
const parsed = {};
if (actionMappings.length > 0) {
parsed.actionMappings = actionMappings.map((mapping, i) => actionMapping(mapping, `${(0, schema_js_1.at)(path, "actionMappings")}[${i}]`));
}
if (stateMappings.length > 0) {
parsed.stateMappings = stateMappings.map((mapping, i) => stateMapping(mapping, `${(0, schema_js_1.at)(path, "stateMappings")}[${i}]`));
}
return parsed;
},
};
}

View file

@ -1,6 +1,6 @@
import { Capability } from "../device/Capability.js"; import { Capability } from "../device/Capability.js";
import type { CapabilityJson } from "../device/Capability.js"; import type { CapabilityJson } from "../device/Capability.js";
import type { Semantics } from "../registry/types.js"; import type { Label, Semantics } from "../registry/types.js";
import type { ActionMapping } from "./ActionMapping.js"; import type { ActionMapping } from "./ActionMapping.js";
import type { AlexaInterfaceType } from "./enums.js"; import type { AlexaInterfaceType } from "./enums.js";
/** One ModeController mode as discovery lists it (configuration.supportedModes): the value plus its friendly names. */ /** One ModeController mode as discovery lists it (configuration.supportedModes): the value plus its friendly names. */
@ -19,7 +19,11 @@ export interface SupportedMode {
} }
interface Options { interface Options {
semantics?: Semantics; semantics?: Semantics;
supportedModes?: Array<string | SupportedMode>; supportedModes?: Array<{
value: string;
friendlyNames: Label[];
}>;
ordered?: boolean;
} }
/** /**
* A capability as 1.x declares it: device.addCapability(type, options), then the add and set methods below. It is a * A capability as 1.x declares it: device.addCapability(type, options), then the add and set methods below. It is a
@ -33,8 +37,14 @@ export declare class AlexaInterface extends Capability<any, any, Options> {
get type(): AlexaInterfaceType; get type(): AlexaInterfaceType;
addActionMapping(mapping: ActionMapping): void; addActionMapping(mapping: ActionMapping): void;
addFriendlyName(name: string, locale: string): void; addFriendlyName(name: string, locale: string): void;
/** The modes of a ModeController, as { value, modeResources } objects. */ /**
addSupportedModes(modes: Array<string | SupportedMode>): void; * The modes of a ModeController, as { value, modeResources } objects. A mode given as a string is announced as
* { value } and noted: Alexa wants friendly names for it. ordered is true unless options.ordered says otherwise,
* as 1.x announced every mode list; with device.add() the default is false.
*/
addSupportedModes(modes: Array<string | SupportedMode>, options?: {
ordered?: boolean;
}): void;
setInstance(name: string): void; setInstance(name: string): void;
getType(): AlexaInterfaceType; getType(): AlexaInterfaceType;
/** @deprecated The same as getType(). */ /** @deprecated The same as getType(). */

View file

@ -25,9 +25,19 @@ export class AlexaInterface extends Capability {
addFriendlyName(name, locale) { addFriendlyName(name, locale) {
this.friendlyNames.push(text(name, locale)); this.friendlyNames.push(text(name, locale));
} }
/** The modes of a ModeController, as { value, modeResources } objects. */ /**
addSupportedModes(modes) { * The modes of a ModeController, as { value, modeResources } objects. A mode given as a string is announced as
this.options.supportedModes = modes; * { value } and noted: Alexa wants friendly names for it. ordered is true unless options.ordered says otherwise,
* as 1.x announced every mode list; with device.add() the default is false.
*/
addSupportedModes(modes, options = {}) {
this.options.ordered = options.ordered ?? true;
this.options.supportedModes = modes.map((mode) => {
if (typeof mode !== "string")
return { value: mode.value, friendlyNames: (mode.modeResources?.friendlyNames ?? []) };
this.notes.push(`the mode ${mode} was given as a string, pass { value, modeResources }`);
return { value: mode, friendlyNames: [] };
});
} }
setInstance(name) { setInstance(name) {
this.instance = name; this.instance = name;

View file

@ -104,6 +104,15 @@ export function checkCapability(capability, descriptor, endpoint) {
if (friendlyNames.length > 0) if (friendlyNames.length > 0)
refuse("takes no friendly names"); refuse("takes no friendly names");
} }
// A capability of device.add() passed the schema when it was declared; one declared the 1.x way did not
if (descriptor.options) {
try {
descriptor.options.parse(capability.options);
}
catch (err) {
refuse(err instanceof SchemaError ? err.message : String(err));
}
}
// generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all // generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all
// controller instances for each endpoint" // controller instances for each endpoint"
const used = new Map(); const used = new Map();

6
dist/esm/index.d.ts vendored
View file

@ -5,11 +5,11 @@ export type { EndpointDefinition, EndpointJson } from "./device/Device.js";
export { Capability } from "./device/Capability.js"; export { Capability } from "./device/Capability.js";
export type { CapabilityJson, CommonOptions, Declaration } from "./device/Capability.js"; export type { CapabilityJson, CommonOptions, Declaration } from "./device/Capability.js";
export { registry, DeclarationError, SchemaError } from "./registry/index.js"; export { registry, DeclarationError, SchemaError } from "./registry/index.js";
export { Alexa, BrightnessController, TemperatureSensor } from "./registry/index.js"; export { Alexa, BrightnessController, ModeController, RangeController, TemperatureSensor, ToggleController, } from "./registry/index.js";
export { PowerController, EndpointHealth } from "./compat/enums.js"; export { PowerController, EndpointHealth } from "./compat/enums.js";
export { asset, text } from "./registry/resources.js"; export { asset, text, semantics, SemanticsBuilder } from "./registry/index.js";
export { ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States, DISPLAY_CATEGORIES as DisplayCategories, } from "./registry/index.js"; export { ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States, DISPLAY_CATEGORIES as DisplayCategories, } from "./registry/index.js";
export type { ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure, ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, Infer, Schema, Temperature, TimeInterval, } from "./registry/index.js"; export type { ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure, ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, ActionName, StateName, Mode, Infer, Schema, Temperature, TimeInterval, } from "./registry/index.js";
export { AlexaInterface } from "./compat/AlexaInterface.js"; export { AlexaInterface } from "./compat/AlexaInterface.js";
export type { SupportedMode } from "./compat/AlexaInterface.js"; export type { SupportedMode } from "./compat/AlexaInterface.js";
export { ActionMapping } from "./compat/ActionMapping.js"; export { ActionMapping } from "./compat/ActionMapping.js";

4
dist/esm/index.js vendored
View file

@ -4,9 +4,9 @@ export { default as Device } from "./device/Device.js";
export { Capability } from "./device/Capability.js"; export { Capability } from "./device/Capability.js";
// The interfaces, for device.add(), and the registry that holds them by name // The interfaces, for device.add(), and the registry that holds them by name
export { registry, DeclarationError, SchemaError } from "./registry/index.js"; export { registry, DeclarationError, SchemaError } from "./registry/index.js";
export { Alexa, BrightnessController, TemperatureSensor } from "./registry/index.js"; export { Alexa, BrightnessController, ModeController, RangeController, TemperatureSensor, ToggleController, } from "./registry/index.js";
export { PowerController, EndpointHealth } from "./compat/enums.js"; export { PowerController, EndpointHealth } from "./compat/enums.js";
export { asset, text } from "./registry/resources.js"; export { asset, text, semantics, SemanticsBuilder } from "./registry/index.js";
// The vocabularies of the Smart Home API // The vocabularies of the Smart Home API
export { ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States, DISPLAY_CATEGORIES as DisplayCategories, } from "./registry/index.js"; export { ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States, DISPLAY_CATEGORIES as DisplayCategories, } from "./registry/index.js";
// 1.x // 1.x

View file

@ -1,8 +1,11 @@
import { Alexa } from "./interfaces/Alexa.js"; import { Alexa } from "./interfaces/Alexa.js";
import { BrightnessController } from "./interfaces/BrightnessController.js"; import { BrightnessController } from "./interfaces/BrightnessController.js";
import { EndpointHealth } from "./interfaces/EndpointHealth.js"; import { EndpointHealth } from "./interfaces/EndpointHealth.js";
import { ModeController } from "./interfaces/ModeController.js";
import { PowerController } from "./interfaces/PowerController.js"; import { PowerController } from "./interfaces/PowerController.js";
import { RangeController } from "./interfaces/RangeController.js";
import { TemperatureSensor } from "./interfaces/TemperatureSensor.js"; import { TemperatureSensor } from "./interfaces/TemperatureSensor.js";
import { ToggleController } from "./interfaces/ToggleController.js";
import type { AnyDescriptor } from "./types.js"; import type { AnyDescriptor } from "./types.js";
export declare const registry: { export declare const registry: {
/** Whether an interface of this name is known. */ /** Whether an interface of this name is known. */
@ -12,7 +15,11 @@ export declare const registry: {
/** Every descriptor, ordered by namespace. */ /** Every descriptor, ordered by namespace. */
list(): AnyDescriptor[]; list(): AnyDescriptor[];
}; };
export { Alexa, BrightnessController, EndpointHealth, PowerController, TemperatureSensor }; export { Alexa, BrightnessController, EndpointHealth, ModeController, PowerController, RangeController, TemperatureSensor, ToggleController, };
export type { Mode } from "./interfaces/ModeController.js";
export { asset, text } from "./resources.js";
export { semantics, SemanticsBuilder } from "./semantics.js";
export type { ActionName, StateName } from "./semantics.js";
export { DeclarationError, defineInterface } from "./types.js"; export { DeclarationError, defineInterface } from "./types.js";
export type { ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, } from "./types.js"; export type { ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, } from "./types.js";
export { s, SchemaError } from "./schema.js"; export { s, SchemaError } from "./schema.js";

View file

@ -2,16 +2,22 @@
import { Alexa } from "./interfaces/Alexa.js"; import { Alexa } from "./interfaces/Alexa.js";
import { BrightnessController } from "./interfaces/BrightnessController.js"; import { BrightnessController } from "./interfaces/BrightnessController.js";
import { EndpointHealth } from "./interfaces/EndpointHealth.js"; import { EndpointHealth } from "./interfaces/EndpointHealth.js";
import { ModeController } from "./interfaces/ModeController.js";
import { PowerController } from "./interfaces/PowerController.js"; import { PowerController } from "./interfaces/PowerController.js";
import { RangeController } from "./interfaces/RangeController.js";
import { TemperatureSensor } from "./interfaces/TemperatureSensor.js"; import { TemperatureSensor } from "./interfaces/TemperatureSensor.js";
import { ToggleController } from "./interfaces/ToggleController.js";
import { STUBS } from "./interfaces/stubs.js"; import { STUBS } from "./interfaces/stubs.js";
import { DeclarationError } from "./types.js"; import { DeclarationError } from "./types.js";
const described = [ const described = [
Alexa, Alexa,
BrightnessController, BrightnessController,
EndpointHealth, EndpointHealth,
ModeController,
PowerController, PowerController,
RangeController,
TemperatureSensor, TemperatureSensor,
ToggleController,
]; ];
const descriptors = new Map(); const descriptors = new Map();
for (const descriptor of [...described, ...STUBS]) { for (const descriptor of [...described, ...STUBS]) {
@ -37,7 +43,9 @@ export const registry = {
return [...descriptors.values()].sort((a, b) => (a.namespace < b.namespace ? -1 : 1)); return [...descriptors.values()].sort((a, b) => (a.namespace < b.namespace ? -1 : 1));
}, },
}; };
export { Alexa, BrightnessController, EndpointHealth, PowerController, TemperatureSensor }; export { Alexa, BrightnessController, EndpointHealth, ModeController, PowerController, RangeController, TemperatureSensor, ToggleController, };
export { asset, text } from "./resources.js";
export { semantics, SemanticsBuilder } from "./semantics.js";
export { DeclarationError, defineInterface } from "./types.js"; export { DeclarationError, defineInterface } from "./types.js";
export { s, SchemaError } from "./schema.js"; export { s, SchemaError } from "./schema.js";
export * from "./catalog.js"; export * from "./catalog.js";

View file

@ -0,0 +1,43 @@
import type { Schema } from "../schema.js";
import type { Label } from "../types.js";
/** One mode: its value and what the user calls it. */
export interface Mode {
value: string;
friendlyNames: Label[];
}
/**
* One of a list of values, under an instance name: the wash cycle of a washer, the position of a garage door. Amazon
* certifies a garage door only with this interface and the display category GARAGE_DOOR.
*/
export declare const ModeController: import("../types.js").InterfaceDescriptor<{
mode: {
name: string;
value: Schema<string | null>;
note: string;
};
}, {
SetMode: {
name: string;
payload: Schema<import("../schema.js").InferShape<{
mode: Schema<string>;
}>>;
};
AdjustMode: {
name: string;
payload: Schema<import("../schema.js").InferShape<{
modeDelta: import("../schema.js").OptionalSchema<number>;
}>>;
when: ({ options }: {
options: {
ordered?: boolean;
};
}) => boolean;
note: string;
};
}, import("../schema.js").InferShape<{
/** At least two. When the modes have an order, in increasing order. */
supportedModes: Schema<Mode[]>;
/** The modes have an order, cold to hot, and the user can say "increase": Alexa sends AdjustMode. Default: false. */
ordered: import("../schema.js").OptionalSchema<boolean>;
semantics: import("../schema.js").OptionalSchema<import("../types.js").Semantics>;
}>, true>;

View file

@ -0,0 +1,84 @@
import { labels } from "../resources.js";
import { at, mismatch, s } from "../schema.js";
import { semanticsOf } from "../semantics.js";
import { DeclarationError, defineInterface } from "../types.js";
const directives = {
SetMode: { name: "SetMode", payload: s.object({ mode: s.string({ min: 1 }) }) },
AdjustMode: {
name: "AdjustMode",
payload: s.object({ modeDelta: s.optional(s.number({ integer: true })) }),
// alexa-modecontroller.html, "Capabilities object": "Modes that have an order support the AdjustMode directive."
when: ({ options }) => options.ordered === true,
note: "modeDelta is the number of modes to move by, 1 when it is left out",
},
};
// A mode is declared as { value, friendlyNames }. The object of discovery and of 1.x, { value, modeResources:
// { friendlyNames } }, is taken as well.
const eitherForm = s.object({
value: s.string({ min: 1 }),
friendlyNames: s.optional(s.unknown()),
modeResources: s.optional(s.object({ friendlyNames: s.unknown() })),
}, { unknownKeys: "reject" });
const mode = {
expects: "a mode { value, friendlyNames }",
parse(input, path = "") {
if (typeof input !== "object" || input === null)
throw mismatch(path, mode.expects, input);
const { value, friendlyNames, modeResources } = eitherForm.parse(input, path);
const named = friendlyNames === undefined && modeResources ? "modeResources.friendlyNames" : "friendlyNames";
return { value, friendlyNames: labels.parse(friendlyNames ?? modeResources?.friendlyNames, at(path, named)) };
},
};
/**
* One of a list of values, under an instance name: the wash cycle of a washer, the position of a garage door. Amazon
* certifies a garage door only with this interface and the display category GARAGE_DOOR.
*/
export const ModeController = defineInterface({
namespace: "Alexa.ModeController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-modecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
mode: { name: "mode", value: s.nullable(s.string({ min: 1 })), note: "null when no mode is set, as when the device is off" },
},
directives,
options: s.object({
/** At least two. When the modes have an order, in increasing order. */
supportedModes: s.array(mode, { min: 2 }),
/** The modes have an order, cold to hot, and the user can say "increase": Alexa sends AdjustMode. Default: false. */
ordered: s.optional(s.boolean()),
semantics: s.optional(semanticsOf({ directives, stateValue: s.string({ min: 1 }) })),
}, { unknownKeys: "reject" }),
// A capability declared the 1.x way may be without modes, or have modes without names
discovery({ options: { supportedModes = [], ordered = false } }) {
if (supportedModes.length === 0)
return {};
const modes = supportedModes.map(({ value, friendlyNames = [] }) => (friendlyNames.length > 0 ? { value, modeResources: { friendlyNames } } : { value }));
return { configuration: { ordered, supportedModes: modes } };
},
validate(capability) {
const { supportedModes, ordered = false, semantics } = capability.options;
const values = supportedModes.map(({ value }) => value);
const twice = values.find((value, i) => values.indexOf(value) !== i);
if (twice !== undefined)
throw new DeclarationError(capability, `the mode ${twice} is listed twice`);
const isMode = (value) => values.includes(value);
for (const { directive } of semantics?.actionMappings ?? []) {
if (directive.name === "AdjustMode" && !ordered) {
throw new DeclarationError(capability, "an action is mapped to AdjustMode, which needs ordered: true");
}
if (directive.name === "SetMode" && !isMode(directive.payload?.mode)) {
throw new DeclarationError(capability, `an action is mapped to SetMode ${directive.payload?.mode}, the modes are ${values.join(", ")}`);
}
}
for (const mapping of semantics?.stateMappings ?? []) {
if (mapping["@type"] === "StatesToValue" && !isMode(mapping.value)) {
throw new DeclarationError(capability, `a state is mapped to ${mapping.value}, the modes are ${values.join(", ")}`);
}
}
},
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -0,0 +1,39 @@
/**
* A number in a range, under an instance name: the position of a blind, the speed of a fan. With nonControllable it
* is a reading the user can ask for, like an air quality index.
*/
export declare const RangeController: import("../types.js").InterfaceDescriptor<{
rangeValue: {
name: string;
value: import("../schema.js").Schema<number>;
};
}, {
SetRangeValue: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{
rangeValue: import("../schema.js").Schema<number>;
}>>;
};
AdjustRangeValue: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{
rangeValueDelta: import("../schema.js").Schema<number>;
rangeValueDeltaDefault: import("../schema.js").Schema<boolean>;
}>>;
note: string;
};
}, import("../schema.js").InferShape<{
/** precision is the step of the range and what "turn up the fan speed" changes it by. */
range: import("../schema.js").Schema<import("../schema.js").InferShape<{
min: import("../schema.js").Schema<number>;
max: import("../schema.js").Schema<number>;
precision: import("../schema.js").Schema<number>;
}>>;
unit: import("../schema.js").OptionalSchema<import("../catalog.js").UnitOfMeasure>;
/** Names for values: "set the fan speed to maximum". */
presets: import("../schema.js").OptionalSchema<import("../schema.js").InferShape<{
value: import("../schema.js").Schema<number>;
friendlyNames: import("../schema.js").Schema<import("../types.js").Label[]>;
}>[]>;
semantics: import("../schema.js").OptionalSchema<import("../types.js").Semantics>;
}>, true>;

View file

@ -0,0 +1,73 @@
import { UNITS_OF_MEASURE } from "../catalog.js";
import { labels } from "../resources.js";
import { s } from "../schema.js";
import { semanticsOf } from "../semantics.js";
import { DeclarationError, defineInterface } from "../types.js";
const directives = {
SetRangeValue: { name: "SetRangeValue", payload: s.object({ rangeValue: s.number() }) },
AdjustRangeValue: {
name: "AdjustRangeValue",
payload: s.object({ rangeValueDelta: s.number(), rangeValueDeltaDefault: s.boolean() }),
note: "rangeValueDeltaDefault is true when the user named no amount; rangeValueDelta is then the precision",
},
};
// 0.1 + 0.2 is not 0.3: a value is on the grid when it is within a millionth of a step of it
function onGrid(value, origin, step) {
const steps = (value - origin) / step;
return Math.abs(steps - Math.round(steps)) < 1e-6;
}
/**
* A number in a range, under an instance name: the position of a blind, the speed of a fan. With nonControllable it
* is a reading the user can ask for, like an air quality index.
*/
export const RangeController = defineInterface({
namespace: "Alexa.RangeController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-rangecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
rangeValue: { name: "rangeValue", value: s.number() },
},
directives,
options: s.object({
/** precision is the step of the range and what "turn up the fan speed" changes it by. */
range: s.object({ min: s.number(), max: s.number(), precision: s.number({ gt: 0 }) }, { unknownKeys: "reject" }),
unit: s.optional(s.oneOf(UNITS_OF_MEASURE, "a unit of measure like Alexa.Unit.Percent")),
/** Names for values: "set the fan speed to maximum". */
presets: s.optional(s.array(s.object({ value: s.number(), friendlyNames: labels }, { unknownKeys: "reject" }))),
semantics: s.optional(semanticsOf({ directives, stateValue: s.number(), ranges: true })),
}, { unknownKeys: "reject" }),
// A capability declared the 1.x way may be without a range; check() says so, discovery lists what there is
discovery({ options: { range, unit, presets } }) {
const configuration = {
...(range && { supportedRange: { minimumValue: range.min, maximumValue: range.max, precision: range.precision } }),
...(unit && { unitOfMeasure: unit }),
...(presets && { presets: presets.map(({ value, friendlyNames }) => ({ rangeValue: value, presetResources: { friendlyNames } })) }),
};
return Object.keys(configuration).length > 0 ? { configuration } : {};
},
validate(capability) {
const { range: { min, max, precision }, presets = [], semantics } = capability.options;
const inRange = (value) => value >= min && value <= max;
if (max <= min)
throw new DeclarationError(capability, `range.max ${max} is not above range.min ${min}`);
for (const { value } of presets) {
// alexa-rangecontroller.html, "Preset object": "minimum range value + (n x precision) where n is an integer"
if (!inRange(value) || !onGrid(value, min, precision)) {
throw new DeclarationError(capability, `the preset ${value} is not ${min} + n x ${precision}, up to ${max}`);
}
}
for (const { directive } of semantics?.actionMappings ?? []) {
const { rangeValue } = directive.payload ?? {};
if (directive.name === "SetRangeValue" && !inRange(rangeValue)) {
throw new DeclarationError(capability, `an action is mapped to SetRangeValue ${rangeValue}, the range is ${min} to ${max}`);
}
}
},
// alexa-rangecontroller.html, "SetRangeValue directive error handling": "If your error is safety related, respond
// with an Alexa.Safety.ErrorResponse"
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -0,0 +1,21 @@
/**
* Something that is on or off, under an instance name: the oscillation of a fan, the light of an oven. The one
* generic controller that Alexa hunches work with (SetEcoOn, SetEcoOff, EcoOn, EcoOff).
*/
export declare const ToggleController: import("../types.js").InterfaceDescriptor<{
toggleState: {
name: string;
value: import("../schema.js").EnumSchema<"ON" | "OFF">;
};
}, {
TurnOn: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{}>>;
};
TurnOff: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{}>>;
};
}, import("../schema.js").InferShape<{
semantics: import("../schema.js").OptionalSchema<import("../types.js").Semantics>;
}>, true>;

View file

@ -0,0 +1,28 @@
import { s } from "../schema.js";
import { semanticsOf } from "../semantics.js";
import { defineInterface } from "../types.js";
const directives = {
TurnOn: { name: "TurnOn", payload: s.object({}) },
TurnOff: { name: "TurnOff", payload: s.object({}) },
};
/**
* Something that is on or off, under an instance name: the oscillation of a fan, the light of an oven. The one
* generic controller that Alexa hunches work with (SetEcoOn, SetEcoOff, EcoOn, EcoOff).
*/
export const ToggleController = defineInterface({
namespace: "Alexa.ToggleController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-togglecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
toggleState: { name: "toggleState", value: s.enum("ON", "OFF") },
},
directives,
options: s.object({
semantics: s.optional(semanticsOf({ directives, stateValue: s.enum("ON", "OFF"), hunches: true })),
}, { unknownKeys: "reject" }),
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -45,7 +45,6 @@ const TABLE = [
["Alexa.Media.PlayQueue", "1", [], "alexa-media-playqueue.html"], ["Alexa.Media.PlayQueue", "1", [], "alexa-media-playqueue.html"],
["Alexa.Media.Playback", "1", [], "alexa-media-playback.html"], ["Alexa.Media.Playback", "1", [], "alexa-media-playback.html"],
["Alexa.Media.Search", "1", [], "alexa-media-search.html"], ["Alexa.Media.Search", "1", [], "alexa-media-search.html"],
["Alexa.ModeController", "3", ["mode"], "alexa-modecontroller.html"],
["Alexa.MotionSensor", "3", [], "alexa-motionsensor.html"], ["Alexa.MotionSensor", "3", [], "alexa-motionsensor.html"],
["Alexa.PercentageController", "3", [], "alexa-percentagecontroller.html"], ["Alexa.PercentageController", "3", [], "alexa-percentagecontroller.html"],
["Alexa.PlaybackController", "3", [], "alexa-playbackcontroller.html"], ["Alexa.PlaybackController", "3", [], "alexa-playbackcontroller.html"],
@ -53,7 +52,6 @@ const TABLE = [
["Alexa.PowerLevelController", "3", [], "alexa-powerlevelcontroller.html"], ["Alexa.PowerLevelController", "3", [], "alexa-powerlevelcontroller.html"],
["Alexa.ProactiveNotificationSource", "1", [], "alexa-proactivenotificationsource.html"], ["Alexa.ProactiveNotificationSource", "1", [], "alexa-proactivenotificationsource.html"],
["Alexa.RTCSessionController", "1", [], "alexa-rtcsessioncontroller.html"], ["Alexa.RTCSessionController", "1", [], "alexa-rtcsessioncontroller.html"],
["Alexa.RangeController", "3", [], "alexa-rangecontroller.html"],
["Alexa.RecordController", "3", [], "alexa-recordcontroller.html"], ["Alexa.RecordController", "3", [], "alexa-recordcontroller.html"],
["Alexa.RemoteVideoPlayer", "1", [], "alexa-remotevideoplayer.html"], ["Alexa.RemoteVideoPlayer", "1", [], "alexa-remotevideoplayer.html"],
["Alexa.SceneController", "3", [], "alexa-scenecontroller.html"], ["Alexa.SceneController", "3", [], "alexa-scenecontroller.html"],
@ -71,13 +69,12 @@ const TABLE = [
["Alexa.ThermostatController.Schedule", "1", [], "alexa-thermostatcontroller-schedule.html"], ["Alexa.ThermostatController.Schedule", "1", [], "alexa-thermostatcontroller-schedule.html"],
// "UNKNOWN" in 1.5.2 as well; the page is titled "Interface 3" // "UNKNOWN" in 1.5.2 as well; the page is titled "Interface 3"
["Alexa.TimeHoldController", "3", [], "alexa-timeholdcontroller.html"], ["Alexa.TimeHoldController", "3", [], "alexa-timeholdcontroller.html"],
["Alexa.ToggleController", "3", ["toggleState"], "alexa-togglecontroller.html"],
["Alexa.UIController", "1", [], "alexa-uicontroller.html"], ["Alexa.UIController", "1", [], "alexa-uicontroller.html"],
["Alexa.UserPreference", "1", [], "alexa-userpreference.html"], ["Alexa.UserPreference", "1", [], "alexa-userpreference.html"],
["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"], ["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"],
["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"], ["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"],
]; ];
// What 1.5.2 added to the capability object of three of them // What 1.5.2 added to the capability object of two of them
const EXTRAS = { const EXTRAS = {
// No properties object; supportsDeactivation and proactivelyReported on the capability itself // No properties object; supportsDeactivation and proactivelyReported on the capability itself
"Alexa.SceneController": ({ proactivelyReported }) => ({ "Alexa.SceneController": ({ proactivelyReported }) => ({
@ -87,9 +84,6 @@ const EXTRAS = {
"Alexa.ThermostatController": () => ({ "Alexa.ThermostatController": () => ({
configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false }, configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false },
}), }),
"Alexa.ModeController": ({ options }) => (options.supportedModes?.length > 0
? { configuration: { ordered: true, supportedModes: options.supportedModes } }
: {}),
}; };
function kindOf(namespace) { function kindOf(namespace) {
if (namespace.endsWith("Sensor")) if (namespace.endsWith("Sensor"))

View file

@ -1,6 +1,6 @@
// Friendly names: what the user calls an instance, a mode or a preset (resources-and-assets.html). // Friendly names: what the user calls an instance, a mode or a preset (resources-and-assets.html).
import { ASSETS, RESERVED_WORDS } from "./catalog.js"; import { ASSETS, RESERVED_WORDS } from "./catalog.js";
import { at, s, SchemaError } from "./schema.js"; import { at, mismatch, s, SchemaError } from "./schema.js";
/** A friendly name as text, in one locale. */ /** A friendly name as text, in one locale. */
export function text(name, locale = "en-US") { export function text(name, locale = "en-US") {
return { "@type": "text", value: { text: name, locale } }; return { "@type": "text", value: { text: name, locale } };
@ -21,6 +21,8 @@ const reserved = RESERVED_WORDS;
export const label = { export const label = {
expects: "a friendly name, from text() or asset()", expects: "a friendly name, from text() or asset()",
parse(input, path = "") { parse(input, path = "") {
if (typeof input !== "object" || input === null)
throw mismatch(path, label.expects, input);
const { "@type": type, value } = typed.parse(input, path); const { "@type": type, value } = typed.parse(input, path);
if (type === "asset") if (type === "asset")
return { "@type": type, value: assetValue.parse(value, at(path, "value")) }; return { "@type": type, value: assetValue.parse(value, at(path, "value")) };

47
dist/esm/registry/semantics.d.ts vendored Normal file
View file

@ -0,0 +1,47 @@
import type { ActionId, StateId } from "./catalog.js";
import type { Schema } from "./schema.js";
import type { ActionsToDirective, Directives, Semantics, StatesToRange, StatesToValue } from "./types.js";
type Short<Id extends string, Prefix extends string> = Id extends `${Prefix}${infer Name}` ? Name : never;
/** A phrase by its id or by its name: "Alexa.Actions.Open" or "Open". */
export type ActionName = ActionId | Short<ActionId, "Alexa.Actions.">;
/** A state by its id or by its name: "Alexa.States.Closed" or "Closed". */
export type StateName = StateId | Short<StateId, "Alexa.States.">;
/**
* Collects the mappings of one capability:
*
* semantics()
* .action("Close", "SetRangeValue", { rangeValue: 0 })
* .action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 })
* .state("Closed", 0)
* .stateRange("Open", 1, 100)
*
* What is collected is checked when the capability is declared, against the directives and the property of its
* interface.
*/
export declare class SemanticsBuilder implements Semantics {
readonly actionMappings: ActionsToDirective[];
readonly stateMappings: Array<StatesToValue | StatesToRange>;
/** The phrases send the directive. payload is its payload; leave it out for a directive that has none. */
action(actions: ActionName | readonly ActionName[], directive: string, payload?: Record<string, unknown>): this;
/** The property at this value is in these states: "is the garage door open?" */
state(states: StateName | readonly StateName[], value: unknown): this;
/** The property between the two values, both included, is in these states. For an interface with a numeric property. */
stateRange(states: StateName | readonly StateName[], minimumValue: number, maximumValue: number): this;
}
export declare function semantics(): SemanticsBuilder;
export interface SemanticsRules {
/** The directives of the interface: a mapping names one of them and gives its payload. */
directives: Directives;
/** The value of the property a state stands for. */
stateValue: Schema<unknown>;
/** States can be mapped to a range of values: the property is a number. */
ranges?: boolean;
/**
* SetEcoOn, SetEcoOff, EcoOn and EcoOff can be mapped. "Semantics for Alexa hunches is supported only for
* Alexa.ToggleController" (generic-controllers.html).
*/
hunches?: boolean;
}
/** The schema of the semantics option of one interface. It takes a semantics() builder or the object as discovery has it. */
export declare function semanticsOf({ directives, stateValue, ranges, hunches }: SemanticsRules): Schema<Semantics>;
export {};

106
dist/esm/registry/semantics.js vendored Normal file
View file

@ -0,0 +1,106 @@
// Semantics of a generic controller: the phrases "open", "close", "raise", "lower" mapped to directives, and states
// like "open" and "closed" mapped to values of the property (alexa-discovery-objects.html, "Semantics object").
import { ACTIONS, STATES } from "./catalog.js";
import { at, mismatch, s, SchemaError } from "./schema.js";
const listed = (given) => (Array.isArray(given) ? [...given] : [given]);
const withPrefix = (prefix, name) => (name.startsWith(prefix) ? name : `${prefix}${name}`);
/**
* Collects the mappings of one capability:
*
* semantics()
* .action("Close", "SetRangeValue", { rangeValue: 0 })
* .action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 })
* .state("Closed", 0)
* .stateRange("Open", 1, 100)
*
* What is collected is checked when the capability is declared, against the directives and the property of its
* interface.
*/
export class SemanticsBuilder {
constructor() {
this.actionMappings = [];
this.stateMappings = [];
}
/** The phrases send the directive. payload is its payload; leave it out for a directive that has none. */
action(actions, directive, payload) {
this.actionMappings.push({
"@type": "ActionsToDirective",
actions: listed(actions).map((name) => withPrefix("Alexa.Actions.", name)),
directive: payload === undefined ? { name: directive } : { name: directive, payload },
});
return this;
}
/** The property at this value is in these states: "is the garage door open?" */
state(states, value) {
this.stateMappings.push({ "@type": "StatesToValue", states: listed(states).map((name) => withPrefix("Alexa.States.", name)), value });
return this;
}
/** The property between the two values, both included, is in these states. For an interface with a numeric property. */
stateRange(states, minimumValue, maximumValue) {
this.stateMappings.push({
"@type": "StatesToRange",
states: listed(states).map((name) => withPrefix("Alexa.States.", name)),
range: { minimumValue, maximumValue },
});
return this;
}
}
export function semantics() {
return new SemanticsBuilder();
}
const isHunch = (id) => /\.(SetEcoOn|SetEcoOff|EcoOn|EcoOff)$/.test(id);
/** The schema of the semantics option of one interface. It takes a semantics() builder or the object as discovery has it. */
export function semanticsOf({ directives, stateValue, ranges = false, hunches = false }) {
const allowed = (ids, what) => {
const choice = ids.filter((id) => hunches || !isHunch(id));
return s.array(s.oneOf(choice, `${what}: ${choice.map((id) => id.split(".")[2]).join(", ")}`), { min: 1 });
};
const names = Object.keys(directives);
const lists = s.object({ actionMappings: s.optional(s.array(s.unknown())), stateMappings: s.optional(s.array(s.unknown())) });
const action = s.object({
"@type": s.literal("ActionsToDirective"),
actions: allowed(ACTIONS, "a phrase of Alexa.Actions"),
directive: s.object({ name: s.oneOf(names, `a directive of the interface: ${names.join(", ")}`) }),
});
const state = s.object({
"@type": ranges ? s.enum("StatesToValue", "StatesToRange") : s.enum("StatesToValue"),
states: allowed(STATES, "a state of Alexa.States"),
});
const range = s.object({ minimumValue: s.number(), maximumValue: s.number() }, { unknownKeys: "reject" });
function actionMapping(input, path) {
const mapping = action.parse(input, path);
const { name, payload } = mapping.directive;
// Checked as the directive will arrive; a mapping without a payload stays without one in discovery
const checked = directives[name].payload.parse(payload ?? {}, at(path, "directive.payload"));
return { "@type": mapping["@type"], actions: mapping.actions, directive: payload === undefined ? { name } : { name, payload: checked } };
}
function stateMapping(input, path) {
const mapping = state.parse(input, path);
if (mapping["@type"] === "StatesToValue") {
return { "@type": mapping["@type"], states: mapping.states, value: stateValue.parse(mapping.value, at(path, "value")) };
}
const { minimumValue, maximumValue } = range.parse(mapping.range, at(path, "range"));
if (minimumValue > maximumValue)
throw new SchemaError(at(path, "range"), `the minimumValue ${minimumValue} is above the maximumValue ${maximumValue}`);
return { "@type": mapping["@type"], states: mapping.states, range: { minimumValue, maximumValue } };
}
const expects = "semantics() with at least one action or state";
return {
expects,
parse(input, path = "") {
if (typeof input !== "object" || input === null)
throw mismatch(path, expects, input);
const { actionMappings = [], stateMappings = [] } = lists.parse(input, path);
if (actionMappings.length + stateMappings.length === 0)
throw mismatch(path, expects, {});
const parsed = {};
if (actionMappings.length > 0) {
parsed.actionMappings = actionMappings.map((mapping, i) => actionMapping(mapping, `${at(path, "actionMappings")}[${i}]`));
}
if (stateMappings.length > 0) {
parsed.stateMappings = stateMappings.map((mapping, i) => stateMapping(mapping, `${at(path, "stateMappings")}[${i}]`));
}
return parsed;
},
};
}

View file

@ -120,7 +120,11 @@ export interface InterfaceDescriptor<P extends Properties = Properties, D extend
events?: Record<string, EventDescriptor>; events?: Record<string, EventDescriptor>;
/** What a declaration can set beyond the fields every capability has: a range, the supported modes. */ /** What a declaration can set beyond the fields every capability has: a range, the supported modes. */
options?: Schema<O>; options?: Schema<O>;
discovery?: (capability: Declared<O>) => CapabilityExtras; /**
* What the interface adds to the capability object. The options may be incomplete: a capability declared the
* 1.x way is announced with what it has, and check() of its device says what is missing.
*/
discovery?: (capability: Declared<Partial<O>>) => CapabilityExtras;
/** The event that answers a directive when it is not Alexa / Response (Arm -> Arm.Response). */ /** The event that answers a directive when it is not Alexa / Response (Arm -> Arm.Response). */
responseFor?: (directive: string) => { responseFor?: (directive: string) => {
namespace: string; namespace: string;
@ -132,7 +136,7 @@ export interface InterfaceDescriptor<P extends Properties = Properties, D extend
errorTypes?: readonly string[]; errorTypes?: readonly string[];
/** Amazon documents a DeferredResponse for the interface. */ /** Amazon documents a DeferredResponse for the interface. */
deferrable?: boolean; deferrable?: boolean;
/** Rules a schema cannot state. Throws DeclarationError. */ /** Rules a schema cannot state, for options that passed the schema. Throws DeclarationError. */
validate?: (capability: Declared<O>, endpoint: EndpointView) => void; validate?: (capability: Declared<O>, endpoint: EndpointView) => void;
} }
export type AnyDescriptor = InterfaceDescriptor<any, any, any, boolean>; export type AnyDescriptor = InterfaceDescriptor<any, any, any, boolean>;

View file

@ -1,6 +1,6 @@
import { Capability } from "../device/Capability.js"; import { Capability } from "../device/Capability.js";
import type { CapabilityJson } from "../device/Capability.js"; import type { CapabilityJson } from "../device/Capability.js";
import type { Semantics } from "../registry/types.js"; import type { Label, Semantics } from "../registry/types.js";
import type { ActionMapping } from "./ActionMapping.js"; import type { ActionMapping } from "./ActionMapping.js";
import type { AlexaInterfaceType } from "./enums.js"; import type { AlexaInterfaceType } from "./enums.js";
/** One ModeController mode as discovery lists it (configuration.supportedModes): the value plus its friendly names. */ /** One ModeController mode as discovery lists it (configuration.supportedModes): the value plus its friendly names. */
@ -19,7 +19,11 @@ export interface SupportedMode {
} }
interface Options { interface Options {
semantics?: Semantics; semantics?: Semantics;
supportedModes?: Array<string | SupportedMode>; supportedModes?: Array<{
value: string;
friendlyNames: Label[];
}>;
ordered?: boolean;
} }
/** /**
* A capability as 1.x declares it: device.addCapability(type, options), then the add and set methods below. It is a * A capability as 1.x declares it: device.addCapability(type, options), then the add and set methods below. It is a
@ -33,8 +37,14 @@ export declare class AlexaInterface extends Capability<any, any, Options> {
get type(): AlexaInterfaceType; get type(): AlexaInterfaceType;
addActionMapping(mapping: ActionMapping): void; addActionMapping(mapping: ActionMapping): void;
addFriendlyName(name: string, locale: string): void; addFriendlyName(name: string, locale: string): void;
/** The modes of a ModeController, as { value, modeResources } objects. */ /**
addSupportedModes(modes: Array<string | SupportedMode>): void; * The modes of a ModeController, as { value, modeResources } objects. A mode given as a string is announced as
* { value } and noted: Alexa wants friendly names for it. ordered is true unless options.ordered says otherwise,
* as 1.x announced every mode list; with device.add() the default is false.
*/
addSupportedModes(modes: Array<string | SupportedMode>, options?: {
ordered?: boolean;
}): void;
setInstance(name: string): void; setInstance(name: string): void;
getType(): AlexaInterfaceType; getType(): AlexaInterfaceType;
/** @deprecated The same as getType(). */ /** @deprecated The same as getType(). */

View file

@ -5,11 +5,11 @@ export type { EndpointDefinition, EndpointJson } from "./device/Device.js";
export { Capability } from "./device/Capability.js"; export { Capability } from "./device/Capability.js";
export type { CapabilityJson, CommonOptions, Declaration } from "./device/Capability.js"; export type { CapabilityJson, CommonOptions, Declaration } from "./device/Capability.js";
export { registry, DeclarationError, SchemaError } from "./registry/index.js"; export { registry, DeclarationError, SchemaError } from "./registry/index.js";
export { Alexa, BrightnessController, TemperatureSensor } from "./registry/index.js"; export { Alexa, BrightnessController, ModeController, RangeController, TemperatureSensor, ToggleController, } from "./registry/index.js";
export { PowerController, EndpointHealth } from "./compat/enums.js"; export { PowerController, EndpointHealth } from "./compat/enums.js";
export { asset, text } from "./registry/resources.js"; export { asset, text, semantics, SemanticsBuilder } from "./registry/index.js";
export { ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States, DISPLAY_CATEGORIES as DisplayCategories, } from "./registry/index.js"; export { ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States, DISPLAY_CATEGORIES as DisplayCategories, } from "./registry/index.js";
export type { ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure, ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, Infer, Schema, Temperature, TimeInterval, } from "./registry/index.js"; export type { ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure, ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, ActionName, StateName, Mode, Infer, Schema, Temperature, TimeInterval, } from "./registry/index.js";
export { AlexaInterface } from "./compat/AlexaInterface.js"; export { AlexaInterface } from "./compat/AlexaInterface.js";
export type { SupportedMode } from "./compat/AlexaInterface.js"; export type { SupportedMode } from "./compat/AlexaInterface.js";
export { ActionMapping } from "./compat/ActionMapping.js"; export { ActionMapping } from "./compat/ActionMapping.js";

View file

@ -1,8 +1,11 @@
import { Alexa } from "./interfaces/Alexa.js"; import { Alexa } from "./interfaces/Alexa.js";
import { BrightnessController } from "./interfaces/BrightnessController.js"; import { BrightnessController } from "./interfaces/BrightnessController.js";
import { EndpointHealth } from "./interfaces/EndpointHealth.js"; import { EndpointHealth } from "./interfaces/EndpointHealth.js";
import { ModeController } from "./interfaces/ModeController.js";
import { PowerController } from "./interfaces/PowerController.js"; import { PowerController } from "./interfaces/PowerController.js";
import { RangeController } from "./interfaces/RangeController.js";
import { TemperatureSensor } from "./interfaces/TemperatureSensor.js"; import { TemperatureSensor } from "./interfaces/TemperatureSensor.js";
import { ToggleController } from "./interfaces/ToggleController.js";
import type { AnyDescriptor } from "./types.js"; import type { AnyDescriptor } from "./types.js";
export declare const registry: { export declare const registry: {
/** Whether an interface of this name is known. */ /** Whether an interface of this name is known. */
@ -12,7 +15,11 @@ export declare const registry: {
/** Every descriptor, ordered by namespace. */ /** Every descriptor, ordered by namespace. */
list(): AnyDescriptor[]; list(): AnyDescriptor[];
}; };
export { Alexa, BrightnessController, EndpointHealth, PowerController, TemperatureSensor }; export { Alexa, BrightnessController, EndpointHealth, ModeController, PowerController, RangeController, TemperatureSensor, ToggleController, };
export type { Mode } from "./interfaces/ModeController.js";
export { asset, text } from "./resources.js";
export { semantics, SemanticsBuilder } from "./semantics.js";
export type { ActionName, StateName } from "./semantics.js";
export { DeclarationError, defineInterface } from "./types.js"; export { DeclarationError, defineInterface } from "./types.js";
export type { ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, } from "./types.js"; export type { ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, } from "./types.js";
export { s, SchemaError } from "./schema.js"; export { s, SchemaError } from "./schema.js";

View file

@ -0,0 +1,43 @@
import type { Schema } from "../schema.js";
import type { Label } from "../types.js";
/** One mode: its value and what the user calls it. */
export interface Mode {
value: string;
friendlyNames: Label[];
}
/**
* One of a list of values, under an instance name: the wash cycle of a washer, the position of a garage door. Amazon
* certifies a garage door only with this interface and the display category GARAGE_DOOR.
*/
export declare const ModeController: import("../types.js").InterfaceDescriptor<{
mode: {
name: string;
value: Schema<string | null>;
note: string;
};
}, {
SetMode: {
name: string;
payload: Schema<import("../schema.js").InferShape<{
mode: Schema<string>;
}>>;
};
AdjustMode: {
name: string;
payload: Schema<import("../schema.js").InferShape<{
modeDelta: import("../schema.js").OptionalSchema<number>;
}>>;
when: ({ options }: {
options: {
ordered?: boolean;
};
}) => boolean;
note: string;
};
}, import("../schema.js").InferShape<{
/** At least two. When the modes have an order, in increasing order. */
supportedModes: Schema<Mode[]>;
/** The modes have an order, cold to hot, and the user can say "increase": Alexa sends AdjustMode. Default: false. */
ordered: import("../schema.js").OptionalSchema<boolean>;
semantics: import("../schema.js").OptionalSchema<import("../types.js").Semantics>;
}>, true>;

View file

@ -0,0 +1,39 @@
/**
* A number in a range, under an instance name: the position of a blind, the speed of a fan. With nonControllable it
* is a reading the user can ask for, like an air quality index.
*/
export declare const RangeController: import("../types.js").InterfaceDescriptor<{
rangeValue: {
name: string;
value: import("../schema.js").Schema<number>;
};
}, {
SetRangeValue: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{
rangeValue: import("../schema.js").Schema<number>;
}>>;
};
AdjustRangeValue: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{
rangeValueDelta: import("../schema.js").Schema<number>;
rangeValueDeltaDefault: import("../schema.js").Schema<boolean>;
}>>;
note: string;
};
}, import("../schema.js").InferShape<{
/** precision is the step of the range and what "turn up the fan speed" changes it by. */
range: import("../schema.js").Schema<import("../schema.js").InferShape<{
min: import("../schema.js").Schema<number>;
max: import("../schema.js").Schema<number>;
precision: import("../schema.js").Schema<number>;
}>>;
unit: import("../schema.js").OptionalSchema<import("../catalog.js").UnitOfMeasure>;
/** Names for values: "set the fan speed to maximum". */
presets: import("../schema.js").OptionalSchema<import("../schema.js").InferShape<{
value: import("../schema.js").Schema<number>;
friendlyNames: import("../schema.js").Schema<import("../types.js").Label[]>;
}>[]>;
semantics: import("../schema.js").OptionalSchema<import("../types.js").Semantics>;
}>, true>;

View file

@ -0,0 +1,21 @@
/**
* Something that is on or off, under an instance name: the oscillation of a fan, the light of an oven. The one
* generic controller that Alexa hunches work with (SetEcoOn, SetEcoOff, EcoOn, EcoOff).
*/
export declare const ToggleController: import("../types.js").InterfaceDescriptor<{
toggleState: {
name: string;
value: import("../schema.js").EnumSchema<"ON" | "OFF">;
};
}, {
TurnOn: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{}>>;
};
TurnOff: {
name: string;
payload: import("../schema.js").Schema<import("../schema.js").InferShape<{}>>;
};
}, import("../schema.js").InferShape<{
semantics: import("../schema.js").OptionalSchema<import("../types.js").Semantics>;
}>, true>;

47
dist/types/registry/semantics.d.ts vendored Normal file
View file

@ -0,0 +1,47 @@
import type { ActionId, StateId } from "./catalog.js";
import type { Schema } from "./schema.js";
import type { ActionsToDirective, Directives, Semantics, StatesToRange, StatesToValue } from "./types.js";
type Short<Id extends string, Prefix extends string> = Id extends `${Prefix}${infer Name}` ? Name : never;
/** A phrase by its id or by its name: "Alexa.Actions.Open" or "Open". */
export type ActionName = ActionId | Short<ActionId, "Alexa.Actions.">;
/** A state by its id or by its name: "Alexa.States.Closed" or "Closed". */
export type StateName = StateId | Short<StateId, "Alexa.States.">;
/**
* Collects the mappings of one capability:
*
* semantics()
* .action("Close", "SetRangeValue", { rangeValue: 0 })
* .action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 })
* .state("Closed", 0)
* .stateRange("Open", 1, 100)
*
* What is collected is checked when the capability is declared, against the directives and the property of its
* interface.
*/
export declare class SemanticsBuilder implements Semantics {
readonly actionMappings: ActionsToDirective[];
readonly stateMappings: Array<StatesToValue | StatesToRange>;
/** The phrases send the directive. payload is its payload; leave it out for a directive that has none. */
action(actions: ActionName | readonly ActionName[], directive: string, payload?: Record<string, unknown>): this;
/** The property at this value is in these states: "is the garage door open?" */
state(states: StateName | readonly StateName[], value: unknown): this;
/** The property between the two values, both included, is in these states. For an interface with a numeric property. */
stateRange(states: StateName | readonly StateName[], minimumValue: number, maximumValue: number): this;
}
export declare function semantics(): SemanticsBuilder;
export interface SemanticsRules {
/** The directives of the interface: a mapping names one of them and gives its payload. */
directives: Directives;
/** The value of the property a state stands for. */
stateValue: Schema<unknown>;
/** States can be mapped to a range of values: the property is a number. */
ranges?: boolean;
/**
* SetEcoOn, SetEcoOff, EcoOn and EcoOff can be mapped. "Semantics for Alexa hunches is supported only for
* Alexa.ToggleController" (generic-controllers.html).
*/
hunches?: boolean;
}
/** The schema of the semantics option of one interface. It takes a semantics() builder or the object as discovery has it. */
export declare function semanticsOf({ directives, stateValue, ranges, hunches }: SemanticsRules): Schema<Semantics>;
export {};

View file

@ -120,7 +120,11 @@ export interface InterfaceDescriptor<P extends Properties = Properties, D extend
events?: Record<string, EventDescriptor>; events?: Record<string, EventDescriptor>;
/** What a declaration can set beyond the fields every capability has: a range, the supported modes. */ /** What a declaration can set beyond the fields every capability has: a range, the supported modes. */
options?: Schema<O>; options?: Schema<O>;
discovery?: (capability: Declared<O>) => CapabilityExtras; /**
* What the interface adds to the capability object. The options may be incomplete: a capability declared the
* 1.x way is announced with what it has, and check() of its device says what is missing.
*/
discovery?: (capability: Declared<Partial<O>>) => CapabilityExtras;
/** The event that answers a directive when it is not Alexa / Response (Arm -> Arm.Response). */ /** The event that answers a directive when it is not Alexa / Response (Arm -> Arm.Response). */
responseFor?: (directive: string) => { responseFor?: (directive: string) => {
namespace: string; namespace: string;
@ -132,7 +136,7 @@ export interface InterfaceDescriptor<P extends Properties = Properties, D extend
errorTypes?: readonly string[]; errorTypes?: readonly string[];
/** Amazon documents a DeferredResponse for the interface. */ /** Amazon documents a DeferredResponse for the interface. */
deferrable?: boolean; deferrable?: boolean;
/** Rules a schema cannot state. Throws DeclarationError. */ /** Rules a schema cannot state, for options that passed the schema. Throws DeclarationError. */
validate?: (capability: Declared<O>, endpoint: EndpointView) => void; validate?: (capability: Declared<O>, endpoint: EndpointView) => void;
} }
export type AnyDescriptor = InterfaceDescriptor<any, any, any, boolean>; export type AnyDescriptor = InterfaceDescriptor<any, any, any, boolean>;

View file

@ -2,7 +2,7 @@ import { Capability } from "../device/Capability.js";
import type { CapabilityJson } from "../device/Capability.js"; import type { CapabilityJson } from "../device/Capability.js";
import { registry } from "../registry/index.js"; import { registry } from "../registry/index.js";
import { text } from "../registry/resources.js"; import { text } from "../registry/resources.js";
import type { Semantics } from "../registry/types.js"; import type { Label, Semantics } from "../registry/types.js";
import type { ActionMapping } from "./ActionMapping.js"; import type { ActionMapping } from "./ActionMapping.js";
import type { AlexaInterfaceType } from "./enums.js"; import type { AlexaInterfaceType } from "./enums.js";
@ -14,7 +14,8 @@ export interface SupportedMode {
interface Options { interface Options {
semantics?: Semantics; semantics?: Semantics;
supportedModes?: Array<string | SupportedMode>; supportedModes?: Array<{ value: string; friendlyNames: Label[] }>;
ordered?: boolean;
} }
/** /**
@ -43,9 +44,18 @@ export class AlexaInterface extends Capability<any, any, Options> {
this.friendlyNames.push(text(name, locale)); this.friendlyNames.push(text(name, locale));
} }
/** The modes of a ModeController, as { value, modeResources } objects. */ /**
addSupportedModes(modes: Array<string | SupportedMode>): void { * The modes of a ModeController, as { value, modeResources } objects. A mode given as a string is announced as
this.options.supportedModes = modes; * { value } and noted: Alexa wants friendly names for it. ordered is true unless options.ordered says otherwise,
* as 1.x announced every mode list; with device.add() the default is false.
*/
addSupportedModes(modes: Array<string | SupportedMode>, options: { ordered?: boolean } = {}): void {
this.options.ordered = options.ordered ?? true;
this.options.supportedModes = modes.map((mode) => {
if (typeof mode !== "string") return { value: mode.value, friendlyNames: (mode.modeResources?.friendlyNames ?? []) as Label[] };
this.notes.push(`the mode ${mode} was given as a string, pass { value, modeResources }`);
return { value: mode, friendlyNames: [] };
});
} }
setInstance(name: string): void { setInstance(name: string): void {

View file

@ -118,6 +118,15 @@ export function checkCapability(capability: Declared<unknown>, descriptor: AnyDe
if (friendlyNames.length > 0) refuse("takes no friendly names"); if (friendlyNames.length > 0) refuse("takes no friendly names");
} }
// A capability of device.add() passed the schema when it was declared; one declared the 1.x way did not
if (descriptor.options) {
try {
descriptor.options.parse(capability.options);
} catch (err) {
refuse(err instanceof SchemaError ? err.message : String(err));
}
}
// generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all // generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all
// controller instances for each endpoint" // controller instances for each endpoint"
const used = new Map<string, Declared>(); const used = new Map<string, Declared>();

View file

@ -8,9 +8,11 @@ export type { CapabilityJson, CommonOptions, Declaration } from "./device/Capabi
// The interfaces, for device.add(), and the registry that holds them by name // The interfaces, for device.add(), and the registry that holds them by name
export { registry, DeclarationError, SchemaError } from "./registry/index.js"; export { registry, DeclarationError, SchemaError } from "./registry/index.js";
export { Alexa, BrightnessController, TemperatureSensor } from "./registry/index.js"; export {
Alexa, BrightnessController, ModeController, RangeController, TemperatureSensor, ToggleController,
} from "./registry/index.js";
export { PowerController, EndpointHealth } from "./compat/enums.js"; export { PowerController, EndpointHealth } from "./compat/enums.js";
export { asset, text } from "./registry/resources.js"; export { asset, text, semantics, SemanticsBuilder } from "./registry/index.js";
// The vocabularies of the Smart Home API // The vocabularies of the Smart Home API
export { export {
@ -21,7 +23,7 @@ export type {
ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure, ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure,
ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor,
InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue, InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue,
Infer, Schema, Temperature, TimeInterval, ActionName, StateName, Mode, Infer, Schema, Temperature, TimeInterval,
} from "./registry/index.js"; } from "./registry/index.js";
// 1.x // 1.x

View file

@ -2,8 +2,11 @@
import { Alexa } from "./interfaces/Alexa.js"; import { Alexa } from "./interfaces/Alexa.js";
import { BrightnessController } from "./interfaces/BrightnessController.js"; import { BrightnessController } from "./interfaces/BrightnessController.js";
import { EndpointHealth } from "./interfaces/EndpointHealth.js"; import { EndpointHealth } from "./interfaces/EndpointHealth.js";
import { ModeController } from "./interfaces/ModeController.js";
import { PowerController } from "./interfaces/PowerController.js"; import { PowerController } from "./interfaces/PowerController.js";
import { RangeController } from "./interfaces/RangeController.js";
import { TemperatureSensor } from "./interfaces/TemperatureSensor.js"; import { TemperatureSensor } from "./interfaces/TemperatureSensor.js";
import { ToggleController } from "./interfaces/ToggleController.js";
import { STUBS } from "./interfaces/stubs.js"; import { STUBS } from "./interfaces/stubs.js";
import { DeclarationError } from "./types.js"; import { DeclarationError } from "./types.js";
import type { AnyDescriptor } from "./types.js"; import type { AnyDescriptor } from "./types.js";
@ -12,8 +15,11 @@ const described: readonly AnyDescriptor[] = [
Alexa, Alexa,
BrightnessController, BrightnessController,
EndpointHealth, EndpointHealth,
ModeController,
PowerController, PowerController,
RangeController,
TemperatureSensor, TemperatureSensor,
ToggleController,
]; ];
const descriptors = new Map<string, AnyDescriptor>(); const descriptors = new Map<string, AnyDescriptor>();
@ -42,7 +48,14 @@ export const registry = {
}, },
}; };
export { Alexa, BrightnessController, EndpointHealth, PowerController, TemperatureSensor }; export {
Alexa, BrightnessController, EndpointHealth, ModeController, PowerController, RangeController, TemperatureSensor,
ToggleController,
};
export type { Mode } from "./interfaces/ModeController.js";
export { asset, text } from "./resources.js";
export { semantics, SemanticsBuilder } from "./semantics.js";
export type { ActionName, StateName } from "./semantics.js";
export { DeclarationError, defineInterface } from "./types.js"; export { DeclarationError, defineInterface } from "./types.js";
export type { export type {
ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor,

View file

@ -0,0 +1,95 @@
import { labels } from "../resources.js";
import { at, mismatch, s } from "../schema.js";
import type { Schema } from "../schema.js";
import { semanticsOf } from "../semantics.js";
import { DeclarationError, defineInterface } from "../types.js";
import type { Label } from "../types.js";
const directives = {
SetMode: { name: "SetMode", payload: s.object({ mode: s.string({ min: 1 }) }) },
AdjustMode: {
name: "AdjustMode",
payload: s.object({ modeDelta: s.optional(s.number({ integer: true })) }),
// alexa-modecontroller.html, "Capabilities object": "Modes that have an order support the AdjustMode directive."
when: ({ options }: { options: { ordered?: boolean } }) => options.ordered === true,
note: "modeDelta is the number of modes to move by, 1 when it is left out",
},
};
/** One mode: its value and what the user calls it. */
export interface Mode {
value: string;
friendlyNames: Label[];
}
// A mode is declared as { value, friendlyNames }. The object of discovery and of 1.x, { value, modeResources:
// { friendlyNames } }, is taken as well.
const eitherForm = s.object({
value: s.string({ min: 1 }),
friendlyNames: s.optional(s.unknown()),
modeResources: s.optional(s.object({ friendlyNames: s.unknown() })),
}, { unknownKeys: "reject" });
const mode: Schema<Mode> = {
expects: "a mode { value, friendlyNames }",
parse(input, path = "") {
if (typeof input !== "object" || input === null) throw mismatch(path, mode.expects, input);
const { value, friendlyNames, modeResources } = eitherForm.parse(input, path);
const named = friendlyNames === undefined && modeResources ? "modeResources.friendlyNames" : "friendlyNames";
return { value, friendlyNames: labels.parse(friendlyNames ?? modeResources?.friendlyNames, at(path, named)) };
},
};
/**
* One of a list of values, under an instance name: the wash cycle of a washer, the position of a garage door. Amazon
* certifies a garage door only with this interface and the display category GARAGE_DOOR.
*/
export const ModeController = defineInterface({
namespace: "Alexa.ModeController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-modecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
mode: { name: "mode", value: s.nullable(s.string({ min: 1 })), note: "null when no mode is set, as when the device is off" },
},
directives,
options: s.object({
/** At least two. When the modes have an order, in increasing order. */
supportedModes: s.array(mode, { min: 2 }),
/** The modes have an order, cold to hot, and the user can say "increase": Alexa sends AdjustMode. Default: false. */
ordered: s.optional(s.boolean()),
semantics: s.optional(semanticsOf({ directives, stateValue: s.string({ min: 1 }) })),
}, { unknownKeys: "reject" }),
// A capability declared the 1.x way may be without modes, or have modes without names
discovery({ options: { supportedModes = [], ordered = false } }) {
if (supportedModes.length === 0) return {};
const modes = supportedModes.map(({ value, friendlyNames = [] }) => (
friendlyNames.length > 0 ? { value, modeResources: { friendlyNames } } : { value }
));
return { configuration: { ordered, supportedModes: modes } };
},
validate(capability) {
const { supportedModes, ordered = false, semantics } = capability.options;
const values = supportedModes.map(({ value }) => value);
const twice = values.find((value, i) => values.indexOf(value) !== i);
if (twice !== undefined) throw new DeclarationError(capability, `the mode ${twice} is listed twice`);
const isMode = (value: unknown): boolean => values.includes(value as string);
for (const { directive } of semantics?.actionMappings ?? []) {
if (directive.name === "AdjustMode" && !ordered) {
throw new DeclarationError(capability, "an action is mapped to AdjustMode, which needs ordered: true");
}
if (directive.name === "SetMode" && !isMode(directive.payload?.mode)) {
throw new DeclarationError(capability, `an action is mapped to SetMode ${directive.payload?.mode}, the modes are ${values.join(", ")}`);
}
}
for (const mapping of semantics?.stateMappings ?? []) {
if (mapping["@type"] === "StatesToValue" && !isMode(mapping.value)) {
throw new DeclarationError(capability, `a state is mapped to ${mapping.value}, the modes are ${values.join(", ")}`);
}
}
},
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -0,0 +1,75 @@
import { UNITS_OF_MEASURE } from "../catalog.js";
import { labels } from "../resources.js";
import { s } from "../schema.js";
import { semanticsOf } from "../semantics.js";
import { DeclarationError, defineInterface } from "../types.js";
const directives = {
SetRangeValue: { name: "SetRangeValue", payload: s.object({ rangeValue: s.number() }) },
AdjustRangeValue: {
name: "AdjustRangeValue",
payload: s.object({ rangeValueDelta: s.number(), rangeValueDeltaDefault: s.boolean() }),
note: "rangeValueDeltaDefault is true when the user named no amount; rangeValueDelta is then the precision",
},
};
// 0.1 + 0.2 is not 0.3: a value is on the grid when it is within a millionth of a step of it
function onGrid(value: number, origin: number, step: number): boolean {
const steps = (value - origin) / step;
return Math.abs(steps - Math.round(steps)) < 1e-6;
}
/**
* A number in a range, under an instance name: the position of a blind, the speed of a fan. With nonControllable it
* is a reading the user can ask for, like an air quality index.
*/
export const RangeController = defineInterface({
namespace: "Alexa.RangeController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-rangecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
rangeValue: { name: "rangeValue", value: s.number() },
},
directives,
options: s.object({
/** precision is the step of the range and what "turn up the fan speed" changes it by. */
range: s.object({ min: s.number(), max: s.number(), precision: s.number({ gt: 0 }) }, { unknownKeys: "reject" }),
unit: s.optional(s.oneOf(UNITS_OF_MEASURE, "a unit of measure like Alexa.Unit.Percent")),
/** Names for values: "set the fan speed to maximum". */
presets: s.optional(s.array(s.object({ value: s.number(), friendlyNames: labels }, { unknownKeys: "reject" }))),
semantics: s.optional(semanticsOf({ directives, stateValue: s.number(), ranges: true })),
}, { unknownKeys: "reject" }),
// A capability declared the 1.x way may be without a range; check() says so, discovery lists what there is
discovery({ options: { range, unit, presets } }) {
const configuration = {
...(range && { supportedRange: { minimumValue: range.min, maximumValue: range.max, precision: range.precision } }),
...(unit && { unitOfMeasure: unit }),
...(presets && { presets: presets.map(({ value, friendlyNames }) => ({ rangeValue: value, presetResources: { friendlyNames } })) }),
};
return Object.keys(configuration).length > 0 ? { configuration } : {};
},
validate(capability) {
const { range: { min, max, precision }, presets = [], semantics } = capability.options;
const inRange = (value: number): boolean => value >= min && value <= max;
if (max <= min) throw new DeclarationError(capability, `range.max ${max} is not above range.min ${min}`);
for (const { value } of presets) {
// alexa-rangecontroller.html, "Preset object": "minimum range value + (n x precision) where n is an integer"
if (!inRange(value) || !onGrid(value, min, precision)) {
throw new DeclarationError(capability, `the preset ${value} is not ${min} + n x ${precision}, up to ${max}`);
}
}
for (const { directive } of semantics?.actionMappings ?? []) {
const { rangeValue } = directive.payload ?? {};
if (directive.name === "SetRangeValue" && !inRange(rangeValue as number)) {
throw new DeclarationError(capability, `an action is mapped to SetRangeValue ${rangeValue}, the range is ${min} to ${max}`);
}
}
},
// alexa-rangecontroller.html, "SetRangeValue directive error handling": "If your error is safety related, respond
// with an Alexa.Safety.ErrorResponse"
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -0,0 +1,30 @@
import { s } from "../schema.js";
import { semanticsOf } from "../semantics.js";
import { defineInterface } from "../types.js";
const directives = {
TurnOn: { name: "TurnOn", payload: s.object({}) },
TurnOff: { name: "TurnOff", payload: s.object({}) },
};
/**
* Something that is on or off, under an instance name: the oscillation of a fan, the light of an oven. The one
* generic controller that Alexa hunches work with (SetEcoOn, SetEcoOff, EcoOn, EcoOff).
*/
export const ToggleController = defineInterface({
namespace: "Alexa.ToggleController",
version: "3",
doc: "https://developer.amazon.com/docs/alexaplus/device-apis/alexa-togglecontroller.html",
kind: "controller",
tier: 1,
instanced: true,
properties: {
toggleState: { name: "toggleState", value: s.enum("ON", "OFF") },
},
directives,
options: s.object({
semantics: s.optional(semanticsOf({ directives, stateValue: s.enum("ON", "OFF"), hunches: true })),
}, { unknownKeys: "reject" }),
errorNamespace: "Alexa.Safety",
errorTypes: ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"],
});

View file

@ -51,7 +51,6 @@ const TABLE: readonly Row[] = [
["Alexa.Media.PlayQueue", "1", [], "alexa-media-playqueue.html"], ["Alexa.Media.PlayQueue", "1", [], "alexa-media-playqueue.html"],
["Alexa.Media.Playback", "1", [], "alexa-media-playback.html"], ["Alexa.Media.Playback", "1", [], "alexa-media-playback.html"],
["Alexa.Media.Search", "1", [], "alexa-media-search.html"], ["Alexa.Media.Search", "1", [], "alexa-media-search.html"],
["Alexa.ModeController", "3", ["mode"], "alexa-modecontroller.html"],
["Alexa.MotionSensor", "3", [], "alexa-motionsensor.html"], ["Alexa.MotionSensor", "3", [], "alexa-motionsensor.html"],
["Alexa.PercentageController", "3", [], "alexa-percentagecontroller.html"], ["Alexa.PercentageController", "3", [], "alexa-percentagecontroller.html"],
["Alexa.PlaybackController", "3", [], "alexa-playbackcontroller.html"], ["Alexa.PlaybackController", "3", [], "alexa-playbackcontroller.html"],
@ -59,7 +58,6 @@ const TABLE: readonly Row[] = [
["Alexa.PowerLevelController", "3", [], "alexa-powerlevelcontroller.html"], ["Alexa.PowerLevelController", "3", [], "alexa-powerlevelcontroller.html"],
["Alexa.ProactiveNotificationSource", "1", [], "alexa-proactivenotificationsource.html"], ["Alexa.ProactiveNotificationSource", "1", [], "alexa-proactivenotificationsource.html"],
["Alexa.RTCSessionController", "1", [], "alexa-rtcsessioncontroller.html"], ["Alexa.RTCSessionController", "1", [], "alexa-rtcsessioncontroller.html"],
["Alexa.RangeController", "3", [], "alexa-rangecontroller.html"],
["Alexa.RecordController", "3", [], "alexa-recordcontroller.html"], ["Alexa.RecordController", "3", [], "alexa-recordcontroller.html"],
["Alexa.RemoteVideoPlayer", "1", [], "alexa-remotevideoplayer.html"], ["Alexa.RemoteVideoPlayer", "1", [], "alexa-remotevideoplayer.html"],
["Alexa.SceneController", "3", [], "alexa-scenecontroller.html"], ["Alexa.SceneController", "3", [], "alexa-scenecontroller.html"],
@ -77,14 +75,13 @@ const TABLE: readonly Row[] = [
["Alexa.ThermostatController.Schedule", "1", [], "alexa-thermostatcontroller-schedule.html"], ["Alexa.ThermostatController.Schedule", "1", [], "alexa-thermostatcontroller-schedule.html"],
// "UNKNOWN" in 1.5.2 as well; the page is titled "Interface 3" // "UNKNOWN" in 1.5.2 as well; the page is titled "Interface 3"
["Alexa.TimeHoldController", "3", [], "alexa-timeholdcontroller.html"], ["Alexa.TimeHoldController", "3", [], "alexa-timeholdcontroller.html"],
["Alexa.ToggleController", "3", ["toggleState"], "alexa-togglecontroller.html"],
["Alexa.UIController", "1", [], "alexa-uicontroller.html"], ["Alexa.UIController", "1", [], "alexa-uicontroller.html"],
["Alexa.UserPreference", "1", [], "alexa-userpreference.html"], ["Alexa.UserPreference", "1", [], "alexa-userpreference.html"],
["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"], ["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"],
["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"], ["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"],
]; ];
// What 1.5.2 added to the capability object of three of them // What 1.5.2 added to the capability object of two of them
const EXTRAS: Record<string, AnyDescriptor["discovery"]> = { const EXTRAS: Record<string, AnyDescriptor["discovery"]> = {
// No properties object; supportsDeactivation and proactivelyReported on the capability itself // No properties object; supportsDeactivation and proactivelyReported on the capability itself
"Alexa.SceneController": ({ proactivelyReported }) => ({ "Alexa.SceneController": ({ proactivelyReported }) => ({
@ -94,9 +91,6 @@ const EXTRAS: Record<string, AnyDescriptor["discovery"]> = {
"Alexa.ThermostatController": () => ({ "Alexa.ThermostatController": () => ({
configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false }, configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false },
}), }),
"Alexa.ModeController": ({ options }) => (options.supportedModes?.length > 0
? { configuration: { ordered: true, supportedModes: options.supportedModes } }
: {}),
}; };
function kindOf(namespace: string): AnyDescriptor["kind"] { function kindOf(namespace: string): AnyDescriptor["kind"] {

View file

@ -1,7 +1,7 @@
// Friendly names: what the user calls an instance, a mode or a preset (resources-and-assets.html). // Friendly names: what the user calls an instance, a mode or a preset (resources-and-assets.html).
import { ASSETS, RESERVED_WORDS } from "./catalog.js"; import { ASSETS, RESERVED_WORDS } from "./catalog.js";
import type { AssetId } from "./catalog.js"; import type { AssetId } from "./catalog.js";
import { at, s, SchemaError } from "./schema.js"; import { at, mismatch, s, SchemaError } from "./schema.js";
import type { Schema } from "./schema.js"; import type { Schema } from "./schema.js";
import type { Label } from "./types.js"; import type { Label } from "./types.js";
@ -28,6 +28,7 @@ const reserved: readonly string[] = RESERVED_WORDS;
export const label: Schema<Label> = { export const label: Schema<Label> = {
expects: "a friendly name, from text() or asset()", expects: "a friendly name, from text() or asset()",
parse(input, path = "") { parse(input, path = "") {
if (typeof input !== "object" || input === null) throw mismatch(path, label.expects, input);
const { "@type": type, value } = typed.parse(input, path); const { "@type": type, value } = typed.parse(input, path);
if (type === "asset") return { "@type": type, value: assetValue.parse(value, at(path, "value")) }; if (type === "asset") return { "@type": type, value: assetValue.parse(value, at(path, "value")) };
const named = textValue.parse(value, at(path, "value")); const named = textValue.parse(value, at(path, "value"));

135
src/registry/semantics.ts Normal file
View file

@ -0,0 +1,135 @@
// Semantics of a generic controller: the phrases "open", "close", "raise", "lower" mapped to directives, and states
// like "open" and "closed" mapped to values of the property (alexa-discovery-objects.html, "Semantics object").
import { ACTIONS, STATES } from "./catalog.js";
import type { ActionId, StateId } from "./catalog.js";
import { at, mismatch, s, SchemaError } from "./schema.js";
import type { Schema } from "./schema.js";
import type { ActionsToDirective, Directives, Semantics, StatesToRange, StatesToValue } from "./types.js";
type Short<Id extends string, Prefix extends string> = Id extends `${Prefix}${infer Name}` ? Name : never;
/** A phrase by its id or by its name: "Alexa.Actions.Open" or "Open". */
export type ActionName = ActionId | Short<ActionId, "Alexa.Actions.">;
/** A state by its id or by its name: "Alexa.States.Closed" or "Closed". */
export type StateName = StateId | Short<StateId, "Alexa.States.">;
const listed = <T>(given: T | readonly T[]): T[] => (Array.isArray(given) ? [...given] : [given as T]);
const withPrefix = (prefix: string, name: string): string => (name.startsWith(prefix) ? name : `${prefix}${name}`);
/**
* Collects the mappings of one capability:
*
* semantics()
* .action("Close", "SetRangeValue", { rangeValue: 0 })
* .action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 })
* .state("Closed", 0)
* .stateRange("Open", 1, 100)
*
* What is collected is checked when the capability is declared, against the directives and the property of its
* interface.
*/
export class SemanticsBuilder implements Semantics {
readonly actionMappings: ActionsToDirective[] = [];
readonly stateMappings: Array<StatesToValue | StatesToRange> = [];
/** The phrases send the directive. payload is its payload; leave it out for a directive that has none. */
action(actions: ActionName | readonly ActionName[], directive: string, payload?: Record<string, unknown>): this {
this.actionMappings.push({
"@type": "ActionsToDirective",
actions: listed(actions).map((name) => withPrefix("Alexa.Actions.", name)),
directive: payload === undefined ? { name: directive } : { name: directive, payload },
});
return this;
}
/** The property at this value is in these states: "is the garage door open?" */
state(states: StateName | readonly StateName[], value: unknown): this {
this.stateMappings.push({ "@type": "StatesToValue", states: listed(states).map((name) => withPrefix("Alexa.States.", name)), value });
return this;
}
/** The property between the two values, both included, is in these states. For an interface with a numeric property. */
stateRange(states: StateName | readonly StateName[], minimumValue: number, maximumValue: number): this {
this.stateMappings.push({
"@type": "StatesToRange",
states: listed(states).map((name) => withPrefix("Alexa.States.", name)),
range: { minimumValue, maximumValue },
});
return this;
}
}
export function semantics(): SemanticsBuilder {
return new SemanticsBuilder();
}
export interface SemanticsRules {
/** The directives of the interface: a mapping names one of them and gives its payload. */
directives: Directives;
/** The value of the property a state stands for. */
stateValue: Schema<unknown>;
/** States can be mapped to a range of values: the property is a number. */
ranges?: boolean;
/**
* SetEcoOn, SetEcoOff, EcoOn and EcoOff can be mapped. "Semantics for Alexa hunches is supported only for
* Alexa.ToggleController" (generic-controllers.html).
*/
hunches?: boolean;
}
const isHunch = (id: string): boolean => /\.(SetEcoOn|SetEcoOff|EcoOn|EcoOff)$/.test(id);
/** The schema of the semantics option of one interface. It takes a semantics() builder or the object as discovery has it. */
export function semanticsOf({ directives, stateValue, ranges = false, hunches = false }: SemanticsRules): Schema<Semantics> {
const allowed = <Id extends string>(ids: readonly Id[], what: string): Schema<Id[]> => {
const choice = ids.filter((id) => hunches || !isHunch(id));
return s.array(s.oneOf(choice, `${what}: ${choice.map((id) => id.split(".")[2]).join(", ")}`), { min: 1 });
};
const names = Object.keys(directives);
const lists = s.object({ actionMappings: s.optional(s.array(s.unknown())), stateMappings: s.optional(s.array(s.unknown())) });
const action = s.object({
"@type": s.literal("ActionsToDirective"),
actions: allowed(ACTIONS, "a phrase of Alexa.Actions"),
directive: s.object({ name: s.oneOf(names, `a directive of the interface: ${names.join(", ")}`) }),
});
const state = s.object({
"@type": ranges ? s.enum("StatesToValue", "StatesToRange") : s.enum("StatesToValue"),
states: allowed(STATES, "a state of Alexa.States"),
});
const range = s.object({ minimumValue: s.number(), maximumValue: s.number() }, { unknownKeys: "reject" });
function actionMapping(input: unknown, path: string): ActionsToDirective {
const mapping = action.parse(input, path);
const { name, payload } = mapping.directive as ActionsToDirective["directive"];
// Checked as the directive will arrive; a mapping without a payload stays without one in discovery
const checked = directives[name].payload.parse(payload ?? {}, at(path, "directive.payload"));
return { "@type": mapping["@type"], actions: mapping.actions, directive: payload === undefined ? { name } : { name, payload: checked } };
}
function stateMapping(input: unknown, path: string): StatesToValue | StatesToRange {
const mapping = state.parse(input, path) as StatesToValue | StatesToRange;
if (mapping["@type"] === "StatesToValue") {
return { "@type": mapping["@type"], states: mapping.states, value: stateValue.parse(mapping.value, at(path, "value")) };
}
const { minimumValue, maximumValue } = range.parse(mapping.range, at(path, "range"));
if (minimumValue > maximumValue) throw new SchemaError(at(path, "range"), `the minimumValue ${minimumValue} is above the maximumValue ${maximumValue}`);
return { "@type": mapping["@type"], states: mapping.states, range: { minimumValue, maximumValue } };
}
const expects = "semantics() with at least one action or state";
return {
expects,
parse(input, path = "") {
if (typeof input !== "object" || input === null) throw mismatch(path, expects, input);
const { actionMappings = [], stateMappings = [] } = lists.parse(input, path);
if (actionMappings.length + stateMappings.length === 0) throw mismatch(path, expects, {});
const parsed: Semantics = {};
if (actionMappings.length > 0) {
parsed.actionMappings = actionMappings.map((mapping, i) => actionMapping(mapping, `${at(path, "actionMappings")}[${i}]`));
}
if (stateMappings.length > 0) {
parsed.stateMappings = stateMappings.map((mapping, i) => stateMapping(mapping, `${at(path, "stateMappings")}[${i}]`));
}
return parsed;
},
};
}

View file

@ -125,7 +125,11 @@ export interface InterfaceDescriptor<
events?: Record<string, EventDescriptor>; events?: Record<string, EventDescriptor>;
/** What a declaration can set beyond the fields every capability has: a range, the supported modes. */ /** What a declaration can set beyond the fields every capability has: a range, the supported modes. */
options?: Schema<O>; options?: Schema<O>;
discovery?: (capability: Declared<O>) => CapabilityExtras; /**
* What the interface adds to the capability object. The options may be incomplete: a capability declared the
* 1.x way is announced with what it has, and check() of its device says what is missing.
*/
discovery?: (capability: Declared<Partial<O>>) => CapabilityExtras;
/** The event that answers a directive when it is not Alexa / Response (Arm -> Arm.Response). */ /** The event that answers a directive when it is not Alexa / Response (Arm -> Arm.Response). */
responseFor?: (directive: string) => { namespace: string; name: string; payload?: Schema<any> } | undefined; responseFor?: (directive: string) => { namespace: string; name: string; payload?: Schema<any> } | undefined;
/** The namespace an ErrorResponse goes under when its type is one of errorTypes. */ /** The namespace an ErrorResponse goes under when its type is one of errorTypes. */
@ -133,7 +137,7 @@ export interface InterfaceDescriptor<
errorTypes?: readonly string[]; errorTypes?: readonly string[];
/** Amazon documents a DeferredResponse for the interface. */ /** Amazon documents a DeferredResponse for the interface. */
deferrable?: boolean; deferrable?: boolean;
/** Rules a schema cannot state. Throws DeclarationError. */ /** Rules a schema cannot state, for options that passed the schema. Throws DeclarationError. */
validate?: (capability: Declared<O>, endpoint: EndpointView) => void; validate?: (capability: Declared<O>, endpoint: EndpointView) => void;
} }

View file

@ -5,7 +5,7 @@ const { test } = require("node:test");
const assert = require("node:assert/strict"); const assert = require("node:assert/strict");
const { const {
Alex2MQTT, ActionMapping, Alexa, AlexaActions, AlexaInterfaceType, BrightnessController, DisplayCategory, EndpointHealth, Alex2MQTT, ActionMapping, Alexa, AlexaActions, AlexaInterfaceType, BrightnessController, DisplayCategory, EndpointHealth,
PowerController, TemperatureSensor, registry, ModeController, PowerController, RangeController, TemperatureSensor, ToggleController, asset, registry, semantics, text,
} = require("alex2node"); } = require("alex2node");
const interfaces = require("../fixtures/interfaces.js"); const interfaces = require("../fixtures/interfaces.js");
const { endpoint } = require("../helpers/endpoint.js"); const { endpoint } = require("../helpers/endpoint.js");
@ -23,13 +23,26 @@ async function discover(alexa, root) {
return alexa.on(`${root}/discover_r`)[before]; return alexa.on(`${root}/discover_r`)[before];
} }
for (const { namespace, page, declared } of interfaces) { // A device with the fields of a zoo endpoint and no capabilities.
test(`${namespace}: device.add() gives the capability object of ${page}.html`, () => { function likeTheZoo(endpointId) {
for (const { options, as: [example, n = 0] } of declared) { const accepted = zoo(endpointId);
const capability = endpoint().add(registry.get(namespace), options); const device = endpoint(endpointId, accepted.friendlyName, accepted.displayCategories);
assert.deepEqual(capability.toJSON(), capabilities(page, namespace, example)[n], `${example}[${n}]`); device.setDescription(accepted.description);
} device.setManufacturerName(accepted.manufacturerName);
device.setManufacturer(accepted.additionalAttributes.manufacturer);
device.setModel(accepted.additionalAttributes.model);
return device;
}
for (const { namespace, page: own, declared } of interfaces) {
for (const { options, example, page = own, n = 0 } of declared) {
test(`${namespace}: device.add() gives the capability object of ${page}.html, ${example}${n > 0 ? ` (${n})` : ""}`, () => {
const device = endpoint();
const capability = device.add(registry.get(namespace), options);
assert.deepEqual(capability.toJSON(), capabilities(page, namespace, example)[n]);
assert.deepEqual(device.check(), []);
}); });
}
} }
test("the fields of a capability object are in the order of the examples: type, interface, version, properties", () => { test("the fields of a capability object are in the order of the examples: type, interface, version, properties", () => {
@ -111,17 +124,115 @@ test("1.x declarations are announced as 1.5.2 announced them, with the Alexa int
}; };
for (const [endpointId, declare] of Object.entries(declarations)) { for (const [endpointId, declare] of Object.entries(declarations)) {
const accepted = zoo(endpointId); const accepted = zoo(endpointId);
const device = endpoint(endpointId, accepted.friendlyName, accepted.displayCategories); const device = likeTheZoo(endpointId);
device.setDescription(accepted.description);
device.setManufacturerName(accepted.manufacturerName);
device.setManufacturer(accepted.additionalAttributes.manufacturer);
device.setModel(accepted.additionalAttributes.model);
declare(device); declare(device);
assert.deepEqual(device.getJSON(), { ...accepted, capabilities: [...accepted.capabilities, ALEXA] }, endpointId); assert.deepEqual(device.getJSON(), { ...accepted, capabilities: [...accepted.capabilities, ALEXA] }, endpointId);
assert.deepEqual(device.check(), [], endpointId); assert.deepEqual(device.check(), [], endpointId);
} }
}); });
test("a RangeController blind declared with device.add() is the zoo's blind, whose JSON was written by hand", () => {
const blinds = likeTheZoo("zoo-blinds");
blinds.add(RangeController, {
instance: "Blind.Lift",
friendlyNames: [asset("Alexa.Setting.Opening")],
range: { min: 0, max: 100, precision: 1 },
unit: "Alexa.Unit.Percent",
semantics: semantics()
.action("Close", "SetRangeValue", { rangeValue: 0 })
.action("Open", "SetRangeValue", { rangeValue: 100 })
.action("Lower", "AdjustRangeValue", { rangeValueDelta: -10, rangeValueDeltaDefault: false })
.action("Raise", "AdjustRangeValue", { rangeValueDelta: 10, rangeValueDeltaDefault: false })
.state("Closed", 0)
.stateRange("Open", 1, 100),
retrievable: true,
proactivelyReported: true,
});
const accepted = zoo("zoo-blinds");
assert.deepEqual(blinds.getJSON(), { ...accepted, capabilities: [...accepted.capabilities, ALEXA] });
assert.deepEqual(blinds.check(), []);
});
test("the zoo's fan and curtain declared with device.add(): a ModeController and a ToggleController with semantics", () => {
const fan = likeTheZoo("zoo-fan");
fan.add(PowerController, { proactivelyReported: true });
fan.add(ModeController, {
instance: "Fan.Speed",
friendlyNames: [text("Speed")],
supportedModes: ["Low", "Medium", "High"].map((name) => ({ value: `Speed.${name}`, friendlyNames: [text(name)] })),
ordered: true,
proactivelyReported: true,
});
assert.deepEqual(fan.getJSON().capabilities, [...zoo("zoo-fan").capabilities, ALEXA]);
const curtain = likeTheZoo("zoo-curtain");
curtain.add(PowerController, { proactivelyReported: true });
curtain.add(ToggleController, {
instance: "Zoo.Shade",
friendlyNames: [text("Shade")],
semantics: semantics().action("Close", "TurnOn").action("Open", "TurnOff"),
proactivelyReported: true,
});
assert.deepEqual(curtain.getJSON().capabilities, [...zoo("zoo-curtain").capabilities, ALEXA]);
});
test("ModeController: the modes are not ordered unless the declaration says so; a mode is declared in either form", () => {
const modes = endpoint("washer-1", "Washer", ["WASHER"]).add(ModeController, {
instance: "Washer.WashCycle",
friendlyNames: [asset("Alexa.Setting.WashCycle")],
supportedModes: [
{ value: "WashCycle.Normal", friendlyNames: [text("Normal"), text("Cottons")] },
{ value: "WashCycle.Delicates", modeResources: { friendlyNames: [asset("Alexa.Value.Delicate"), text("Knits")] } },
],
});
assert.deepEqual(modes.toJSON().configuration, {
ordered: false,
supportedModes: [
{ value: "WashCycle.Normal", modeResources: { friendlyNames: [text("Normal"), text("Cottons")] } },
{ value: "WashCycle.Delicates", modeResources: { friendlyNames: [asset("Alexa.Value.Delicate"), text("Knits")] } },
],
});
});
test("1.x addSupportedModes: ordered as 1.x announced it, or as the second argument says; a string becomes { value }", () => {
const fan = endpoint("fan-1", "Fan", ["FAN"]);
const named = (value) => ({ value, modeResources: { friendlyNames: [{ "@type": "text", value: { text: value, locale: "en-US" } }] } });
const speed = fan.addCapability(AlexaInterfaceType.MODE_CONTROLLER, { instance: "Fan.Speed" });
speed.addFriendlyName("Speed", "en-US");
speed.addSupportedModes([named("Low"), named("High")]);
assert.equal(speed.getJSON().configuration.ordered, true);
const source = fan.addCapability(AlexaInterfaceType.MODE_CONTROLLER, { instance: "Fan.Mode" });
source.addFriendlyName("Mode", "en-US");
source.addSupportedModes([named("Auto"), named("On")], { ordered: false });
assert.deepEqual(source.getJSON().configuration, { ordered: false, supportedModes: [named("Auto"), named("On")] });
assert.deepEqual(fan.check(), []);
const plain = fan.addCapability(AlexaInterfaceType.MODE_CONTROLLER, { instance: "Fan.Timer" });
plain.addFriendlyName("Countdown", "en-US");
plain.addSupportedModes(["Short", named("Long")]);
assert.deepEqual(plain.getJSON().configuration.supportedModes, [{ value: "Short" }, named("Long")]);
assert.deepEqual(fan.check(), [
'fan-1: Alexa.ModeController "Fan.Timer": supportedModes[0].friendlyNames: expected a list with 1 or more entries, got []',
'fan-1: Alexa.ModeController "Fan.Timer": the mode Short was given as a string, pass { value, modeResources }',
]);
});
test("a 1.x RangeController has no way to give its range: announced as 1.5.2 did, with its property now, and check() says it", () => {
const blinds = endpoint("blinds-1", "Blinds", ["INTERIOR_BLIND"]);
const lift = blinds.addCapability(AlexaInterfaceType.RANGE_CONTROLLER, { instance: "Blind.Lift", proactivelyReported: true });
lift.addFriendlyName("Lift", "en-US");
assert.deepEqual(lift.getJSON(), {
type: "AlexaInterface",
interface: "Alexa.RangeController",
instance: "Blind.Lift",
version: "3",
properties: { supported: [{ name: "rangeValue" }], proactivelyReported: true, retrievable: true },
capabilityResources: { friendlyNames: [text("Lift")] },
});
assert.deepEqual(blinds.check(), ['blinds-1: Alexa.RangeController "Blind.Lift": range: expected an object with min, max, precision, got nothing']);
});
test("registerDevice: every endpoint ends with the Alexa interface; alexaInterface: false leaves it out", async () => { test("registerDevice: every endpoint ends with the Alexa interface; alexaInterface: false leaves it out", async () => {
const { alexa, bridge } = await setup(Alex2MQTT, "root"); const { alexa, bridge } = await setup(Alex2MQTT, "root");
const lamp = bridge.registerDevice("Lamp", "lamp-1", DisplayCategory.LIGHT); const lamp = bridge.registerDevice("Lamp", "lamp-1", DisplayCategory.LIGHT);

View file

@ -4,7 +4,8 @@
const { test } = require("node:test"); const { test } = require("node:test");
const assert = require("node:assert/strict"); const assert = require("node:assert/strict");
const { const {
Alex2MQTT, AlexaInterfaceType, BrightnessController, DeclarationError, EndpointHealth, PowerController, TemperatureSensor, registry, ActionMapping, Alex2MQTT, AlexaActions, AlexaInterfaceType, BrightnessController, DeclarationError, EndpointHealth, ModeController,
PowerController, RangeController, TemperatureSensor, ToggleController, asset, registry, semantics, text,
} = require("alex2node"); } = require("alex2node");
const { endpoint } = require("../helpers/endpoint.js"); const { endpoint } = require("../helpers/endpoint.js");
const { setup, sleep } = require("../helpers/harness.js"); const { setup, sleep } = require("../helpers/harness.js");
@ -98,8 +99,11 @@ test("device.add refuses an option the interface does not have and a value that
}); });
test("an endpoint takes 100 capabilities, the ones the library adds among them", () => { test("an endpoint takes 100 capabilities, the ones the library adds among them", () => {
const switches = (device) => {
for (let n = 1; n <= 98; n += 1) device.add(ToggleController, { instance: `Panel.Switch${n}`, friendlyNames: [text(`Switch ${n}`)] });
};
const panel = endpoint("panel-1", "Panel", ["OTHER"]); const panel = endpoint("panel-1", "Panel", ["OTHER"]);
for (let n = 1; n <= 98; n += 1) panel.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: `Panel.Switch${n}` }); switches(panel);
panel.add(PowerController); panel.add(PowerController);
assert.equal(panel.getJSON().capabilities.length, 100); assert.equal(panel.getJSON().capabilities.length, 100);
assert.deepEqual(panel.check(), []); assert.deepEqual(panel.check(), []);
@ -114,7 +118,7 @@ test("an endpoint takes 100 capabilities, the ones the library adds among them",
// With Alexa.EndpointHealth added for the device there is room for 98 // With Alexa.EndpointHealth added for the device there is room for 98
const health = endpoint("panel-2", "Panel", ["OTHER"]); const health = endpoint("panel-2", "Panel", ["OTHER"]);
health.endpointHealth = true; health.endpointHealth = true;
for (let n = 1; n <= 98; n += 1) health.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: `Panel.Switch${n}` }); switches(health);
assert.equal(refused(() => health.add(PowerController)).message, "panel-2: 101 capabilities, an endpoint takes 100"); assert.equal(refused(() => health.add(PowerController)).message, "panel-2: 101 capabilities, an endpoint takes 100");
assert.doesNotThrow(() => health.add(EndpointHealth)); assert.doesNotThrow(() => health.add(EndpointHealth));
}); });
@ -127,12 +131,166 @@ test("check() lists what is wrong with a device declared the 1.x way, one line f
fan.addCapability(AlexaInterfaceType.POWER_CONTROLLER, { instance: "Fan.Power" }); fan.addCapability(AlexaInterfaceType.POWER_CONTROLLER, { instance: "Fan.Power" });
fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Oscillate" }); fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Oscillate" });
fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Oscillate" }); fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Oscillate" });
fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER).addFriendlyName("Light", "en-US");
fan.addCapability(AlexaInterfaceType.RANGE_CONTROLLER, { instance: "Fan.Speed" }).addFriendlyName("Speed", "en-US");
const mode = fan.addCapability(AlexaInterfaceType.MODE_CONTROLLER, { instance: "Fan.Mode" });
mode.addFriendlyName("Volume", "en-US");
mode.addSupportedModes(["Auto"]);
const direction = fan.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER, { instance: "Fan.Direction" });
direction.addFriendlyName("Speed", "en-US");
direction.addActionMapping(new ActionMapping([AlexaActions.Open], "Reverse"));
assert.deepEqual(fan.check(), [ assert.deepEqual(fan.check(), [
'fan-1: "VEHICLE" is not a display category', 'fan-1: "VEHICLE" is not a display category',
'fan-1: Alexa.PowerController "Fan.Power": takes no instance name: an endpoint has the interface once', 'fan-1: Alexa.PowerController "Fan.Power": takes no instance name: an endpoint has the interface once',
'fan-1: Alexa.ToggleController "Fan.Oscillate": needs a friendly name, from text() or asset()',
'fan-1: Alexa.ToggleController "Fan.Oscillate": the instance is declared twice', 'fan-1: Alexa.ToggleController "Fan.Oscillate": the instance is declared twice',
"fan-1: Alexa.ToggleController: needs an instance name, like Blind.Lift",
'fan-1: Alexa.RangeController "Fan.Speed": range: expected an object with min, max, precision, got nothing',
'fan-1: Alexa.ModeController "Fan.Mode": friendlyNames[0].value.text: "Volume" is a reserved word, not to be used as a friendly name',
'fan-1: Alexa.ModeController "Fan.Mode": the mode Auto was given as a string, pass { value, modeResources }',
'fan-1: Alexa.ToggleController "Fan.Direction": the first friendly name, Speed, is the first of Alexa.RangeController "Fan.Speed" too',
]); ]);
assert.equal(fan.getJSON().capabilities.length, 4, "announced all the same"); assert.equal(fan.getJSON().capabilities.length, 8, "announced all the same");
});
// A blind with a lift from 0 to 100: what each case below declares on top of it
const LIFT = { instance: "Blind.Lift", friendlyNames: [asset("Alexa.Setting.Opening")], range: { min: 0, max: 100, precision: 5 } };
const POSITION = {
instance: "Blind.Position",
friendlyNames: [text("Position")],
supportedModes: [
{ value: "Position.Up", friendlyNames: [asset("Alexa.Value.Open")] },
{ value: "Position.Down", friendlyNames: [asset("Alexa.Value.Close")] },
],
};
const TILT = { instance: "Blind.Tilt", friendlyNames: [text("Tilt")] };
const without = (options, ...keys) => Object.fromEntries(Object.entries(options).filter(([key]) => !keys.includes(key)));
test("a generic controller needs an instance name and a friendly name, and each instance is declared once", () => {
const cases = [
[RangeController, without(LIFT, "instance"), "Alexa.RangeController: needs an instance name, like Blind.Lift"],
[ModeController, without(POSITION, "instance"), "Alexa.ModeController: needs an instance name, like Blind.Lift"],
[ToggleController, { ...TILT, instance: "" }, "Alexa.ToggleController: needs an instance name, like Blind.Lift"],
[RangeController, without(LIFT, "friendlyNames"), 'Alexa.RangeController "Blind.Lift": needs a friendly name, from text() or asset()'],
[ModeController, { ...POSITION, friendlyNames: [] }, 'Alexa.ModeController "Blind.Position": needs a friendly name, from text() or asset()'],
[ToggleController, without(TILT, "friendlyNames"), 'Alexa.ToggleController "Blind.Tilt": needs a friendly name, from text() or asset()'],
];
for (const [descriptor, options, message] of cases) {
assert.equal(refused(() => endpoint("blinds-1").add(descriptor, options)).message, `blinds-1: ${message}`);
}
const blinds = endpoint("blinds-1");
blinds.add(ToggleController, TILT);
assert.equal(
refused(() => blinds.add(ToggleController, { ...TILT, friendlyNames: [text("Slats")] })).message,
'blinds-1: Alexa.ToggleController "Blind.Tilt": the instance is declared twice'
);
// The same instance name under another interface is another capability
blinds.add(RangeController, { ...LIFT, instance: "Blind.Tilt" });
assert.equal(blinds.getCapabilities().length, 2);
});
test("friendly names: an asset of the catalog or a text with a locale, no reserved word, the first one once on the endpoint", () => {
const named = (...friendlyNames) => () => endpoint("blinds-1").add(ToggleController, { ...TILT, friendlyNames });
const cases = [
[named(text("volume")), 'friendlyNames[0].value.text: "volume" is a reserved word, not to be used as a friendly name'],
[named(text("Tilt"), text("Night Light")), 'friendlyNames[1].value.text: "Night Light" is a reserved word, not to be used as a friendly name'],
[named(asset("Alexa.Setting.Tilt")), 'friendlyNames[0].value.assetId: expected an id of the global Alexa catalog, like Alexa.Setting.Opening, got "Alexa.Setting.Tilt"'],
[named(text("Tilt", "english")), 'friendlyNames[0].value.locale: expected a locale like en-US, got "english"'],
[named(text("")), 'friendlyNames[0].value.text: expected a string of 1 or more characters, got ""'],
[named("Tilt"), 'friendlyNames[0]: expected a friendly name, from text() or asset(), got "Tilt"'],
[named({ "@type": "name", value: "Tilt" }), 'friendlyNames[0].@type: expected text | asset, got "name"'],
];
for (const [declare, message] of cases) assert.equal(refused(declare).message, `blinds-1: Alexa.ToggleController "Blind.Tilt": ${message}`);
const blinds = endpoint("blinds-1");
blinds.add(RangeController, LIFT);
blinds.add(ToggleController, TILT);
assert.equal(
refused(() => blinds.add(ModeController, { ...POSITION, friendlyNames: [text("tilt"), text("Position")] })).message,
'blinds-1: Alexa.ModeController "Blind.Position": the first friendly name, tilt, is the first of Alexa.ToggleController "Blind.Tilt" too'
);
assert.equal(
refused(() => blinds.add(ModeController, { ...POSITION, friendlyNames: [asset("Alexa.Setting.Opening")] })).message,
'blinds-1: Alexa.ModeController "Blind.Position": the first friendly name, Alexa.Setting.Opening, is the first of Alexa.RangeController "Blind.Lift" too'
);
// Second names may repeat, and the same text in another language is another name
blinds.add(ModeController, { ...POSITION, friendlyNames: [text("Tilt", "en-GB"), text("Tilt")] });
assert.equal(blinds.getCapabilities().length, 3);
});
test("RangeController: a range, presets on its grid, a unit of measure", () => {
const lift = (options) => () => endpoint("blinds-1").add(RangeController, { ...LIFT, ...options });
const preset = (value) => ({ value, friendlyNames: [text("Half")] });
const cases = [
[() => endpoint("blinds-1").add(RangeController, without(LIFT, "range")), "range: expected an object with min, max, precision, got nothing"],
[lift({ range: { min: 0, max: 100 } }), "range.precision: expected a number greater than 0, got nothing"],
[lift({ range: { min: 0, max: 100, precision: 0 } }), "range.precision: expected a number greater than 0, got 0"],
[lift({ range: { min: 0, max: 100, step: 5 } }), "range.step: unknown key, the known ones are min, max, precision"],
[lift({ range: { min: 100, max: 0, precision: 5 } }), "range.max 0 is not above range.min 100"],
[lift({ presets: [preset(50), preset(52)] }), "the preset 52 is not 0 + n x 5, up to 100"],
[lift({ presets: [preset(105)] }), "the preset 105 is not 0 + n x 5, up to 100"],
[lift({ presets: [{ value: 50 }] }), "presets[0].friendlyNames: expected a list with 1 or more entries, got nothing"],
[lift({ presets: [{ value: 50, friendlyNames: [text("Timer")] }] }), 'presets[0].friendlyNames[0].value.text: "Timer" is a reserved word, not to be used as a friendly name'],
[lift({ unit: "Alexa.Unit.Percentage" }), 'unit: expected a unit of measure like Alexa.Unit.Percent, got "Alexa.Unit.Percentage"'],
[lift({ preset: [] }), "preset: unknown key, the known ones are range, unit, presets, semantics"],
[lift({ semantics: semantics().action("Open", "SetRangeValue", { rangeValue: 1000 }) }), "an action is mapped to SetRangeValue 1000, the range is 0 to 100"],
];
for (const [declare, message] of cases) assert.equal(refused(declare).message, `blinds-1: Alexa.RangeController "Blind.Lift": ${message}`);
// A grid that does not start at 0, and one of tenths
const fan = endpoint("fan-1");
fan.add(RangeController, { ...LIFT, range: { min: 1, max: 10, precision: 3 }, presets: [preset(1), preset(4), preset(10)] });
fan.add(RangeController, {
instance: "Fan.Angle",
friendlyNames: [text("Angle")],
range: { min: 0, max: 1, precision: 0.1 },
presets: [{ value: 0.3, friendlyNames: [text("Narrow")] }, { value: 0.7, friendlyNames: [text("Wide")] }],
});
assert.equal(fan.getCapabilities().length, 2);
});
test("ModeController: two modes or more, each once, and mappings to modes it has", () => {
const position = (options) => () => endpoint("blinds-1").add(ModeController, { ...POSITION, ...options });
const [up, down] = POSITION.supportedModes;
const cases = [
[() => endpoint("blinds-1").add(ModeController, without(POSITION, "supportedModes")), "supportedModes: expected a list with 2 or more entries, got nothing"],
[position({ supportedModes: [up] }), /^supportedModes: expected a list with 2 or more entries, got \[\{"value":"Position\.Up"/],
[position({ supportedModes: [up, down, up] }), "the mode Position.Up is listed twice"],
[position({ supportedModes: [up, { value: "Position.Down" }] }), "supportedModes[1].friendlyNames: expected a list with 1 or more entries, got nothing"],
[position({ supportedModes: [up, "Position.Down"] }), 'supportedModes[1]: expected a mode { value, friendlyNames }, got "Position.Down"'],
[position({ ordered: "yes" }), 'ordered: expected true or false, got "yes"'],
[position({ semantics: semantics().action("Open", "SetMode", { mode: "Position.Open" }) }), "an action is mapped to SetMode Position.Open, the modes are Position.Up, Position.Down"],
[position({ semantics: semantics().state("Closed", "Position.Closed") }), "a state is mapped to Position.Closed, the modes are Position.Up, Position.Down"],
[position({ semantics: semantics().action("Raise", "AdjustMode", { modeDelta: 1 }) }), "an action is mapped to AdjustMode, which needs ordered: true"],
];
for (const [declare, message] of cases) {
const prefix = 'blinds-1: Alexa.ModeController "Blind.Position": ';
if (typeof message === "string") assert.equal(refused(declare).message, prefix + message);
else assert.match(refused(declare).message.slice(prefix.length), message);
}
const ordered = position({ ordered: true, semantics: semantics().action("Raise", "AdjustMode", { modeDelta: -1 }) })();
const unordered = position({})();
const { AdjustMode } = ModeController.directives;
assert.deepEqual([AdjustMode.when(ordered), AdjustMode.when(unordered)], [true, false], "Alexa sends AdjustMode to an ordered mode only");
});
test("a phrase is mapped once on an endpoint, across its Range, Mode and Toggle capabilities", () => {
const blinds = endpoint("blinds-1");
blinds.add(RangeController, { ...LIFT, semantics: semantics().action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 }) });
assert.equal(
refused(() => blinds.add(ToggleController, { ...TILT, semantics: semantics().action("Close", "TurnOff").action("Open", "TurnOn") })).message,
'blinds-1: Alexa.ToggleController "Blind.Tilt": Alexa.Actions.Open is mapped here and on Alexa.RangeController "Blind.Lift", an endpoint maps a phrase once'
);
assert.equal(
refused(() => blinds.add(ModeController, { ...POSITION, semantics: semantics().action("Lower", "SetMode", { mode: "Position.Down" }).action(["Close", "Lower"], "SetMode", { mode: "Position.Down" }) })).message,
'blinds-1: Alexa.ModeController "Blind.Position": Alexa.Actions.Lower is mapped twice, an endpoint maps a phrase once'
);
blinds.add(ToggleController, { ...TILT, semantics: semantics().action("Close", "TurnOff").action("Lower", "TurnOff") });
// Another endpoint maps the same phrases
endpoint("blinds-2").add(ToggleController, { ...TILT, semantics: semantics().action("Open", "TurnOn") });
}); });
test("a stub is declared like any interface and checked for nothing but being declared twice", () => { test("a stub is declared like any interface and checked for nothing but being declared twice", () => {

View file

@ -0,0 +1,13 @@
{
"@type": "ActionsToDirective",
"actions": [
"Alexa.Actions.Close",
"Alexa.Actions.Lower"
],
"directive": {
"name": "SetRangeValue",
"payload": {
"rangeValue": 0
}
}
}

View file

@ -0,0 +1,51 @@
{
"semantics": {
"actionMappings": [
{
"@type": "ActionsToDirective",
"actions": [
"Alexa.Actions.Close",
"Alexa.Actions.Lower"
],
"directive": {
"name": "SetRangeValue",
"payload": {
"rangeValue": 0
}
}
},
{
"@type": "ActionsToDirective",
"actions": [
"Alexa.Actions.Open",
"Alexa.Actions.Raise"
],
"directive": {
"name": "SetRangeValue",
"payload": {
"rangeValue": 100
}
}
}
],
"stateMappings": [
{
"@type": "StatesToValue",
"states": [
"Alexa.States.Closed"
],
"value": 0
},
{
"@type": "StatesToRange",
"states": [
"Alexa.States.Open"
],
"range": {
"minimumValue": 1,
"maximumValue": 100
}
}
]
}
}

View file

@ -0,0 +1,10 @@
{
"@type": "StatesToRange",
"states": [
"Alexa.States.Open"
],
"range": {
"minimumValue": 1,
"maximumValue": 100
}
}

View file

@ -0,0 +1,23 @@
{
"directive": {
"header": {
"namespace": "Alexa.ModeController",
"instance": "Washer.WashTemperature",
"name": "AdjustMode",
"messageId": "Unique version 4 UUID",
"correlationToken": "Opaque correlation token",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID",
"cookie": {}
},
"payload": {
"modeDelta": 1
}
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.ModeController",
"instance": "Washer.WashTemperature",
"name": "mode",
"value": "WashTemperature.Warm",
"timeOfSample": "2017-02-03T16:20:00.00Z",
"uncertaintyInMilliseconds": 0
}
]
}
}

View file

@ -0,0 +1,43 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "ChangeReport",
"messageId": "Unique identifier, preferably a version 4 UUID",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {
"change": {
"cause": {
"type": "PHYSICAL_INTERACTION"
},
"properties": [
{
"namespace": "Alexa.ModeController",
"instance": "Washer.WashTemperature",
"name": "mode",
"value": "WashTemperature.Hot",
"timeOfSample": "2024-02-03T17:10:50.52Z",
"uncertaintyInMilliseconds": 0
}
]
}
}
},
"context": {
"namespace": "Alexa.EndpointHealth",
"name": "connectivity",
"value": {
"value": "OK"
},
"timeOfSample": "2024-02-03T17:08:20.12Z",
"uncertaintyInMilliseconds": 10000
}
}

View file

@ -0,0 +1,23 @@
{
"directive": {
"header": {
"namespace": "Alexa.ModeController",
"instance": "Washer.WashCycle",
"name": "SetMode",
"messageId": "Unique version 4 UUID",
"correlationToken": "Opaque correlation token",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID",
"cookie": {}
},
"payload": {
"mode": "WashCycle.Normal"
}
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.ModeController",
"instance": "Washer.WashCycle",
"name": "mode",
"value": "WashCycle.Normal",
"timeOfSample": "2017-02-03T16:20:00.00Z",
"uncertaintyInMilliseconds": 0
}
]
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "StateReport",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.ModeController",
"instance": "Washer.WashCycle",
"name": "mode",
"value": "WashCycle.Delicates",
"timeOfSample": "2017-02-03T16:20:00.00Z",
"uncertaintyInMilliseconds": 0
}
]
}
}

View file

@ -0,0 +1,6 @@
{
"namespace": "Alexa.ModeController",
"name": "mode",
"instance": "Washer.WashTemperature",
"value": "WashTemperature.Cold"
}

View file

@ -0,0 +1,24 @@
{
"directive": {
"header": {
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "AdjustRangeValue",
"messageId": "Unique version 4 UUID",
"correlationToken": "Opaque correlation token",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID",
"cookie": {}
},
"payload": {
"rangeValueDelta": -5,
"rangeValueDeltaDefault": false
}
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "rangeValue",
"value": 10,
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
}
]
}
}

View file

@ -0,0 +1,50 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "ChangeReport",
"messageId": "Unique identifier, preferably a version 4 UUID",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {
"change": {
"cause": {
"type": "PHYSICAL_INTERACTION"
},
"properties": [
{
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "rangeValue",
"value": 0,
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
},
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": "OFF",
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 0
}
]
}
}
},
"context": {
"namespace": "Alexa.EndpointHealth",
"name": "connectivity",
"value": {
"value": "OK"
},
"timeOfSample": "2017-02-03T16:20:00.00Z",
"uncertaintyInMilliseconds": 60000
}
}

View file

@ -0,0 +1,23 @@
{
"directive": {
"header": {
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "SetRangeValue",
"messageId": "Unique version 4 UUID",
"correlationToken": "Opaque correlation token",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID",
"cookie": {}
},
"payload": {
"rangeValue": 7
}
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "rangeValue",
"value": 7,
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
}
]
}
}

View file

@ -0,0 +1,38 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "StateReport",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "rangeValue",
"value": 4,
"timeOfSample": "2017-02-03T16:21:00.00Z",
"uncertaintyInMilliseconds": 500
},
{
"namespace": "Alexa.PowerController",
"name": "powerState",
"value": "ON",
"timeOfSample": "2017-02-03T16:20:00.00Z",
"uncertaintyInMilliseconds": 0
}
]
}
}

View file

@ -0,0 +1,6 @@
{
"namespace": "Alexa.RangeController",
"instance": "Fan.Speed",
"name": "rangeValue",
"value": 10
}

View file

@ -0,0 +1,51 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "ChangeReport",
"messageId": "Unique identifier, preferably a version 4 UUID",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {
"change": {
"cause": {
"type": "PHYSICAL_INTERACTION"
},
"properties": [
{
"namespace": "Alexa.ToggleController",
"instance": "Oven.OvenLight",
"name": "toggleState",
"value": "OFF",
"timeOfSample": "2017-02-04T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
},
{
"namespace": "Alexa.ToggleController",
"instance": "Stovetop.ResidualHeat",
"name": "toggleState",
"value": "ON",
"timeOfSample": "2017-02-04T16:20:50.42Z",
"uncertaintyInMilliseconds": 500
}
]
}
}
},
"context": {
"namespace": "Alexa.EndpointHealth",
"name": "connectivity",
"value": {
"value": "OK"
},
"timeOfSample": "2017-02-04T16:00:00.00Z",
"uncertaintyInMilliseconds": 0
}
}

View file

@ -0,0 +1,39 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "StateReport",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.ToggleController",
"instance": "Stovetop.ResidualHeat",
"name": "toggleState",
"value": "OFF",
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
},
{
"namespace": "Alexa.ToggleController",
"instance": "Oven.Light",
"name": "toggleState",
"value": "ON",
"timeOfSample": "2017-02-04T08:00:00.10Z",
"uncertaintyInMilliseconds": 500
}
]
}
}

View file

@ -0,0 +1,21 @@
{
"directive": {
"header": {
"namespace": "Alexa.ToggleController",
"instance": "Oven.Light",
"name": "TurnOff",
"messageId": "Unique version 4 UUID",
"correlationToken": "Opaque correlation token",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID",
"cookie": {}
},
"payload": {}
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.ToggleController",
"instance": "Oven.Light",
"name": "toggleState",
"value": "OFF",
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
}
]
}
}

View file

@ -0,0 +1,21 @@
{
"directive": {
"header": {
"namespace": "Alexa.ToggleController",
"instance": "Oven.Light",
"name": "TurnOn",
"messageId": "Unique version 4 UUID",
"correlationToken": "Opaque correlation token",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID",
"cookie": {}
},
"payload": {}
}
}

View file

@ -0,0 +1,31 @@
{
"event": {
"header": {
"namespace": "Alexa",
"name": "Response",
"messageId": "Unique identifier, preferably a version 4 UUID",
"correlationToken": "Opaque correlation token that matches the request",
"payloadVersion": "3"
},
"endpoint": {
"scope": {
"type": "BearerToken",
"token": "OAuth2.0 bearer token"
},
"endpointId": "Endpoint ID"
},
"payload": {}
},
"context": {
"properties": [
{
"namespace": "Alexa.ToggleController",
"instance": "Oven.Light",
"name": "toggleState",
"value": "ON",
"timeOfSample": "2017-02-03T16:20:50.52Z",
"uncertaintyInMilliseconds": 500
}
]
}
}

View file

@ -0,0 +1,127 @@
{
"event": {
"header": {
"namespace": "Alexa.Discovery",
"name": "Discover.Response",
"payloadVersion": "3",
"messageId": "Unique identifier, preferably a version 4 UUID"
},
"payload": {
"endpoints": [
{
"endpointId": "Unique ID of the endpoint",
"manufacturerName": "Kitchen Appliance Plus",
"description": "Smart Oven by Kitchen Appliance Plus",
"friendlyName": "Oven",
"displayCategories": [
"OVEN"
],
"cookie": {},
"capabilities": [
{
"type": "AlexaInterface",
"interface": "Alexa.ToggleController",
"instance": "Oven.OvenLight",
"version": "3",
"properties": {
"supported": [
{
"name": "toggleState"
}
],
"proactivelyReported": true,
"retrievable": true,
"nonControllable": false
},
"capabilityResources": {
"friendlyNames": [
{
"@type": "text",
"value": {
"text": "Oven light",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Luz del horno",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Lumière du four",
"locale": "fr-CA"
}
}
]
}
},
{
"type": "AlexaInterface",
"interface": "Alexa.ToggleController",
"instance": "Stovetop.ResidualHeat",
"version": "3",
"properties": {
"supported": [
{
"name": "toggleState"
}
],
"proactivelyReported": true,
"retrievable": true,
"nonControllable": true
},
"capabilityResources": {
"friendlyNames": [
{
"@type": "text",
"value": {
"text": "Stovetop is still hot",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Todavía está caliente",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Encore chaude",
"locale": "fr-CA"
}
}
]
}
},
{
"type": "AlexaInterface",
"interface": "Alexa.EndpointHealth",
"version": "3",
"properties": {
"supported": [
{
"name": "connectivity"
}
],
"proactivelyReported": true,
"retrievable": true
}
},
{
"type": "AlexaInterface",
"interface": "Alexa",
"version": "3"
}
]
}
]
}
}
}

View file

@ -0,0 +1,247 @@
{
"event": {
"header": {
"namespace": "Alexa.Discovery",
"name": "Discover.Response",
"payloadVersion": "3",
"messageId": "Unique identifier, preferably a version 4 UUID"
},
"payload": {
"endpoints": [
{
"endpointId": "Unique ID of the endpoint",
"friendlyName": "Tower Fan",
"description": "Tower Fan by Sample Manufacturer",
"manufacturerName": "Sample Manufacturer",
"displayCategories": [
"FAN"
],
"cookie": {},
"capabilities": [
{
"type": "AlexaInterface",
"interface": "Alexa.ToggleController",
"version": "3",
"instance": "SampleManufacturer.Fan.Oscillate",
"capabilityResources": {
"friendlyNames": [
{
"@type": "asset",
"value": {
"assetId": "Alexa.Setting.Oscillate"
}
},
{
"@type": "text",
"value": {
"text": "Rotate",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Rotation",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Girar",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Rotation",
"locale": "fr-CA"
}
}
]
},
"properties": {
"proactivelyReported": true,
"retrievable": true,
"supported": [
{
"name": "toggleState"
}
]
}
},
{
"type": "AlexaInterface",
"interface": "Alexa.RangeController",
"version": "3",
"instance": "SampleManufacturer.Fan.Speed",
"capabilityResources": {
"friendlyNames": [
{
"@type": "asset",
"value": {
"assetId": "Alexa.Setting.FanSpeed"
}
},
{
"@type": "text",
"value": {
"text": "Speed",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Velocidad",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Vitesse",
"locale": "fr-CA"
}
}
]
},
"properties": {
"supported": [
{
"name": "rangeValue"
}
],
"proactivelyReported": true,
"retrievable": true
},
"configuration": {
"supportedRange": {
"minimumValue": 1,
"maximumValue": 10,
"precision": 1
},
"presets": [
{
"rangeValue": 10,
"presetResources": {
"friendlyNames": [
{
"@type": "asset",
"value": {
"assetId": "Alexa.Value.Maximum"
}
},
{
"@type": "asset",
"value": {
"assetId": "Alexa.Value.High"
}
},
{
"@type": "text",
"value": {
"text": "Highest",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Fast",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Alta",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Élevée",
"locale": "fr-CA"
}
}
]
}
},
{
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{
"@type": "asset",
"value": {
"assetId": "Alexa.Value.Minimum"
}
},
{
"@type": "asset",
"value": {
"assetId": "Alexa.Value.Low"
}
},
{
"@type": "text",
"value": {
"text": "Lowest",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Slow",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Baja",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Faible",
"locale": "fr-CA"
}
}
]
}
}
]
}
},
{
"type": "AlexaInterface",
"interface": "Alexa.PowerController",
"version": "3",
"properties": {
"supported": [
{
"name": "powerState"
}
],
"proactivelyReported": true,
"retrievable": true
}
},
{
"type": "AlexaInterface",
"interface": "Alexa",
"version": "3"
}
]
}
]
}
}
}

View file

@ -0,0 +1,111 @@
{
"event": {
"header": {
"namespace": "Alexa.Discovery",
"name": "Discover.Response",
"payloadVersion": "3",
"messageId": "Unique identifier, preferably a version 4 UUID"
},
"payload": {
"endpoints": [
{
"endpointId": "Unique ID of the endpoint",
"manufacturerName": "manufacturer name",
"description": "Smart Garbage Can by Manufacturer",
"friendlyName": "garbage can",
"displayCategories": [
"OTHER"
],
"cookie": {},
"capabilities": [
{
"type": "AlexaInterface",
"interface": "Alexa.ToggleController",
"instance": "GarbageCan.Lid",
"version": "3",
"properties": {
"supported": [
{
"name": "toggleState"
}
],
"proactivelyReported": true,
"retrievable": true
},
"capabilityResources": {
"friendlyNames": [
{
"@type": "text",
"value": {
"text": "Garbage can lid",
"locale": "en-US"
}
},
{
"@type": "text",
"value": {
"text": "Tapa del bote de basura",
"locale": "es-MX"
}
},
{
"@type": "text",
"value": {
"text": "Couvercle de poubelle",
"locale": "fr-CA"
}
}
]
},
"semantics": {
"actionMappings": [
{
"@type": "ActionsToDirective",
"actions": [
"Alexa.Actions.Close"
],
"directive": {
"name": "TurnOff",
"payload": {}
}
},
{
"@type": "ActionsToDirective",
"actions": [
"Alexa.Actions.Open"
],
"directive": {
"name": "TurnOn",
"payload": {}
}
}
],
"stateMappings": [
{
"@type": "StatesToValue",
"states": [
"Alexa.States.Closed"
],
"value": "OFF"
},
{
"@type": "StatesToValue",
"states": [
"Alexa.States.Open"
],
"value": "ON"
}
]
}
},
{
"type": "AlexaInterface",
"interface": "Alexa",
"version": "3"
}
]
}
]
}
}
}

View file

@ -0,0 +1,6 @@
{
"namespace": "Alexa.ToggleController",
"instance": "Oven.OvenLight",
"name": "toggleState",
"value": "ON"
}

View file

@ -1,20 +1,101 @@
"use strict"; "use strict";
// One entry per interface that is described in full: the page its examples were saved from (test/helpers/fixtures.js) // One entry per interface that is described in full: the page its examples were saved from (test/helpers/fixtures.js)
// and declarations that give capability objects of those examples. // and declarations that give capability objects of Amazon's discovery examples.
// //
// namespace the interface // namespace the interface
// page the page of the interface; test/fixtures/alexa-docs/<page>/ has its examples // page the page of the interface; test/fixtures/alexa-docs/<page>/ has its examples
// declared [{ options, as: [example, n] }]: device.add(descriptor, options) gives the n-th capability object of // declared [{ options, example, page, n }]: device.add(descriptor, options) gives the n-th capability object of
// the interface in that discovery example (n counts from 0 and defaults to it) // the interface in that discovery example. n counts from 0 and defaults to it, page defaults to the
// page of the interface. The pages of RangeController and ModeController fold their discovery
// examples away, so they were not saved: the range is taken from an example of the ToggleController
// page, and ModeController has none.
// //
// test/registry/descriptors.test.js and test/device/discovery.test.js run the entries. The first one fails for a // test/registry/descriptors.test.js and test/device/discovery.test.js run the entries. The first one fails for a
// descriptor of tier 1 or 2 that has no entry. // descriptor of tier 1 or 2 that has no entry.
const { asset, semantics, text } = require("alex2node");
const reported = { retrievable: true, proactivelyReported: true }; const reported = { retrievable: true, proactivelyReported: true };
const inThreeLanguages = (english, spanish, french) => [text(english, "en-US"), text(spanish, "es-MX"), text(french, "fr-CA")];
module.exports = [ module.exports = [
{ namespace: "Alexa", page: "alexa-interface", declared: [{ options: {}, as: ["discovery"] }] }, { namespace: "Alexa", page: "alexa-interface", declared: [{ options: {}, example: "discovery" }] },
{ namespace: "Alexa.BrightnessController", page: "alexa-brightnesscontroller", declared: [{ options: reported, as: ["discovery"] }] }, { namespace: "Alexa.BrightnessController", page: "alexa-brightnesscontroller", declared: [{ options: reported, example: "discovery" }] },
{ namespace: "Alexa.EndpointHealth", page: "alexa-endpointhealth", declared: [{ options: reported, as: ["discovery"] }] }, { namespace: "Alexa.EndpointHealth", page: "alexa-endpointhealth", declared: [{ options: reported, example: "discovery" }] },
{ namespace: "Alexa.PowerController", page: "alexa-powercontroller", declared: [{ options: reported, as: ["discovery"] }] }, { namespace: "Alexa.ModeController", page: "alexa-modecontroller", declared: [] },
{ namespace: "Alexa.TemperatureSensor", page: "alexa-temperaturesensor", declared: [{ options: reported, as: ["discovery"] }] }, { namespace: "Alexa.PowerController", page: "alexa-powercontroller", declared: [{ options: reported, example: "discovery" }] },
{
namespace: "Alexa.RangeController",
page: "alexa-rangecontroller",
declared: [{
page: "alexa-togglecontroller",
example: "discovery-range-and-toggle",
options: {
...reported,
instance: "SampleManufacturer.Fan.Speed",
friendlyNames: [asset("Alexa.Setting.FanSpeed"), ...inThreeLanguages("Speed", "Velocidad", "Vitesse")],
range: { min: 1, max: 10, precision: 1 },
presets: [
{
value: 10,
friendlyNames: [
asset("Alexa.Value.Maximum"), asset("Alexa.Value.High"), text("Highest"), text("Fast"), text("Alta", "es-MX"),
text("Élevée", "fr-CA"),
],
},
{
value: 1,
friendlyNames: [
asset("Alexa.Value.Minimum"), asset("Alexa.Value.Low"), text("Lowest"), text("Slow"), text("Baja", "es-MX"),
text("Faible", "fr-CA"),
],
},
],
},
}],
},
{ namespace: "Alexa.TemperatureSensor", page: "alexa-temperaturesensor", declared: [{ options: reported, example: "discovery" }] },
{
namespace: "Alexa.ToggleController",
page: "alexa-togglecontroller",
declared: [
{
example: "discovery-oven",
options: {
...reported,
nonControllable: false,
instance: "Oven.OvenLight",
friendlyNames: inThreeLanguages("Oven light", "Luz del horno", "Lumière du four"),
},
},
{
example: "discovery-oven",
n: 1,
options: {
...reported,
nonControllable: true,
instance: "Stovetop.ResidualHeat",
friendlyNames: inThreeLanguages("Stovetop is still hot", "Todavía está caliente", "Encore chaude"),
},
},
{
example: "discovery-semantics",
options: {
...reported,
instance: "GarbageCan.Lid",
friendlyNames: inThreeLanguages("Garbage can lid", "Tapa del bote de basura", "Couvercle de poubelle"),
semantics: semantics().action("Close", "TurnOff", {}).action("Open", "TurnOn", {}).state("Closed", "OFF").state("Open", "ON"),
},
},
{
example: "discovery-range-and-toggle",
options: {
...reported,
instance: "SampleManufacturer.Fan.Oscillate",
friendlyNames: [
asset("Alexa.Setting.Oscillate"), text("Rotate"), text("Rotation"), text("Girar", "es-MX"), text("Rotation", "fr-CA"),
],
},
},
],
},
]; ];

View file

@ -3,7 +3,7 @@
// declaration stops rejecting what follows it. // declaration stops rejecting what follows it.
import { import {
ActionMapping, AlexaActions, AlexaInterfaceType, Assets, BrightnessController, DeclarationError, DisplayCategory, EndpointHealth, ActionMapping, AlexaActions, AlexaInterfaceType, Assets, BrightnessController, DeclarationError, DisplayCategory, EndpointHealth,
PowerController, PowerState, TemperatureSensor, asset, registry, text, ModeController, PowerController, PowerState, RangeController, TemperatureSensor, ToggleController, asset, registry, semantics, text,
} from "alex2node"; } from "alex2node";
import type { import type {
Alex2MQTT, Alex2MQTTOptions, AlexaInterface, AlexaStatusMessage, AssetId, Capability, CapabilityJson, ChangeCause, Device, Alex2MQTT, Alex2MQTTOptions, AlexaInterface, AlexaStatusMessage, AssetId, Capability, CapabilityJson, ChangeCause, Device,
@ -74,6 +74,44 @@ const names: Label[] = [asset("Alexa.Setting.Opening"), text("Position"), text("
// @ts-expect-error not in the global Alexa catalog // @ts-expect-error not in the global Alexa catalog
asset("Alexa.Setting.Openning"); asset("Alexa.Setting.Openning");
// The generic controllers: an instance name, friendly names and the options of the interface
const lift = blinds.add(RangeController, {
instance: "Blind.Lift",
friendlyNames: names,
range: { min: 0, max: 100, precision: 1 },
unit: "Alexa.Unit.Percent",
presets: [{ value: 100, friendlyNames: [asset("Alexa.Value.Maximum")] }],
semantics: semantics()
.action("Close", "SetRangeValue", { rangeValue: 0 })
.action(["Open", AlexaActions.Raise], "SetRangeValue", { rangeValue: 100 })
.state("Closed", 0)
.stateRange("Open", 1, 100),
retrievable: true,
proactivelyReported: true,
});
blinds.add(ModeController, {
instance: "Blind.Position",
friendlyNames: [text("Position")],
supportedModes: [{ value: "Position.Up", friendlyNames: [asset("Alexa.Value.Open")] }, { value: "Position.Down", friendlyNames: [asset("Alexa.Value.Close")] }],
ordered: false,
});
blinds.add(ToggleController, { instance: "Blind.Tilt", friendlyNames: [text("Tilt")], nonControllable: true });
// @ts-expect-error a range controller has a range
blinds.add(RangeController, { instance: "Blind.Tilt", friendlyNames: [text("Tilt")] });
// @ts-expect-error a generic controller has an instance name and friendly names
blinds.add(ToggleController, { proactivelyReported: true });
// @ts-expect-error and so it cannot be declared without options
blinds.add(ToggleController);
// @ts-expect-error not a unit of measure
blinds.add(RangeController, { instance: "Blind.Tilt", friendlyNames: [text("Tilt")], range: { min: 0, max: 90, precision: 1 }, unit: "Alexa.Unit.Percentage" });
// @ts-expect-error not a phrase Alexa has
semantics().action("Shut", "TurnOff");
// What a directive carries and what a property holds are typed by the descriptor
const lower: Infer<typeof RangeController.directives.AdjustRangeValue.payload> = { rangeValueDelta: -10, rangeValueDeltaDefault: false };
const position: Schema<number> = lift.descriptor.properties.rangeValue.value;
// @ts-expect-error a mode is a string, or null when none is set
const current: Infer<typeof ModeController.properties.mode.value> = 3;
// The registry: a descriptor by its namespace or by the 1.x enum member // The registry: a descriptor by its namespace or by the 1.x enum member
const described: InterfaceDescriptor = registry.get("Alexa.PowerController"); const described: InterfaceDescriptor = registry.get("Alexa.PowerController");
const version: string = registry.get(AlexaInterfaceType.ENDPOINT_HEALTH).version; const version: string = registry.get(AlexaInterfaceType.ENDPOINT_HEALTH).version;
@ -95,6 +133,6 @@ const measured: Infer<typeof temperature> = { value: 20, scale: "CELSIUS" };
const rankine: Infer<typeof temperature> = { value: 20, scale: "RANKINE" }; const rankine: Infer<typeof temperature> = { value: 20, scale: "RANKINE" };
export { export {
options, added, chained, sent, on, namespace, reachable, announced, endpoint, problems, names, version, refused, opening, options, added, chained, sent, on, namespace, reachable, announced, endpoint, problems, names, lower, position, current, version,
percent, vacuum, misspelt, notAUnit, measured, rankine, refused, opening, percent, vacuum, misspelt, notAUnit, measured, rankine,
}; };

View file

@ -30,16 +30,20 @@ test("a descriptor of tier 1 or 2 has an entry in test/fixtures/interfaces.js, a
assert.deepEqual(described.map((descriptor) => descriptor.namespace), interfaces.map((entry) => entry.namespace).sort()); assert.deepEqual(described.map((descriptor) => descriptor.namespace), interfaces.map((entry) => entry.namespace).sort());
}); });
for (const { namespace, page } of interfaces) { for (const { namespace, page, declared } of interfaces) {
test(`${namespace}: version, properties, directive payloads and property values of ${page}.html`, () => { test(`${namespace}: version, properties, directive payloads and property values of ${page}.html`, () => {
const descriptor = registry.get(namespace); const descriptor = registry.get(namespace);
assert.ok(descriptor.doc.endsWith(`/${page}.html`), descriptor.doc); assert.ok(descriptor.doc.endsWith(`/${page}.html`), descriptor.doc);
for (const name of examples(page).filter((example) => example.startsWith("discovery"))) { // The discovery examples of the page, and of another page when the entry declares from one
for (const capability of capabilities(page, namespace, name)) { const discovery = examples(page).filter((example) => example.startsWith("discovery")).map((example) => [page, example]);
assert.equal(capability.version, descriptor.version, `${name}: version`); for (const { page: other = page, example } of declared) discovery.push([other, example]);
for (const [from, example] of discovery) {
for (const capability of capabilities(from, namespace, example)) {
assert.equal(capability.version, descriptor.version, `${example}: version`);
assert.equal("instance" in capability, descriptor.instanced, `${example}: instance`);
const supported = capability.properties ? capability.properties.supported.map((property) => property.name) : []; const supported = capability.properties ? capability.properties.supported.map((property) => property.name) : [];
for (const property of supported) assert.ok(property in descriptor.properties, `${name}: ${property}`); assert.deepEqual(supported, Object.keys(descriptor.properties), `${example}: properties`);
} }
} }
@ -64,6 +68,19 @@ for (const { namespace, page } of interfaces) {
}); });
} }
test("the error types of an interface are in the error type table under its error namespace", () => {
const { ERROR_TYPES } = require("../../dist/cjs/registry/catalog.js");
const withErrors = registry.list().filter((descriptor) => descriptor.errorNamespace || descriptor.errorTypes);
// The generic controllers answer a safety problem under Alexa.Safety
for (const name of ["Alexa.ModeController", "Alexa.RangeController", "Alexa.ToggleController"]) {
assert.deepEqual(registry.get(name).errorTypes, ["OBSTACLE_DETECTED", "SAFETY_BEAM_BREACHED"], name);
}
for (const { namespace, errorNamespace, errorTypes } of withErrors) {
assert.ok(errorTypes.length > 0, namespace);
for (const type of errorTypes) assert.equal(ERROR_TYPES[type], errorNamespace, `${namespace}: ${type}`);
}
});
test("Alexa.EndpointHealth is version 3.1 and reports connectivity, with a reason when it has one", () => { test("Alexa.EndpointHealth is version 3.1 and reports connectivity, with a reason when it has one", () => {
const { version, properties } = registry.get("Alexa.EndpointHealth"); const { version, properties } = registry.get("Alexa.EndpointHealth");
assert.equal(version, "3.1"); assert.equal(version, "3.1");

View file

@ -0,0 +1,104 @@
"use strict";
// semantics(): the mappings of phrases to directives and of states to values, as discovery lists them.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const { Actions, AlexaActions, ModeController, RangeController, SchemaError, States, ToggleController, semantics } = require("alex2node");
const { doc } = require("../helpers/fixtures.js");
// The schema of the semantics option of an interface, and the message of the SchemaError it throws.
const semanticsOf = (descriptor) => ({
parse: (input) => descriptor.options.parse({ ...COMPLETE[descriptor.namespace], semantics: input }).semantics,
});
const COMPLETE = {
"Alexa.RangeController": { range: { min: 0, max: 100, precision: 1 } },
"Alexa.ModeController": {
supportedModes: ["Up", "Down"].map((name) => ({ value: `Position.${name}`, friendlyNames: [{ "@type": "text", value: { text: name, locale: "en-US" } }] })),
},
"Alexa.ToggleController": {},
};
function refusal(descriptor, input) {
try {
semanticsOf(descriptor).parse(input);
} catch (err) {
assert.ok(err instanceof SchemaError, `threw ${err}`);
return err.message;
}
return assert.fail("the semantics were accepted");
}
test("semantics() builds the Semantics object of alexa-discovery-objects.html", () => {
const built = semantics()
.action(["Close", "Lower"], "SetRangeValue", { rangeValue: 0 })
.action(["Open", "Raise"], "SetRangeValue", { rangeValue: 100 })
.state("Closed", 0)
.stateRange("Open", 1, 100);
const { semantics: example } = doc("alexa-discovery-objects", "semantics");
assert.deepEqual(semanticsOf(RangeController).parse(built), example);
assert.deepEqual(built.actionMappings[0], doc("alexa-discovery-objects", "actionMapping"));
assert.deepEqual(built.stateMappings[1], doc("alexa-discovery-objects", "stateMapping"));
// What the schema returns is the plain object, and it takes that object as it takes the builder
assert.equal(Object.getPrototypeOf(semanticsOf(RangeController).parse(built)), Object.prototype);
assert.deepEqual(semanticsOf(RangeController).parse(example), example);
});
test("a phrase and a state are given by name, by id or by the AlexaActions enum of 1.x", () => {
const { actionMappings, stateMappings } = semantics()
.action("Open", "TurnOn")
.action("Alexa.Actions.Close", "TurnOff")
.action([AlexaActions.Raise, Actions[3]], "TurnOn")
.state(["Closed", States[0]], "OFF");
assert.deepEqual(actionMappings.map((mapping) => mapping.actions), [
["Alexa.Actions.Open"], ["Alexa.Actions.Close"], ["Alexa.Actions.Raise", "Alexa.Actions.Lower"],
]);
assert.deepEqual(stateMappings[0].states, ["Alexa.States.Closed", "Alexa.States.Open"]);
// No payload given, none in discovery; an empty one is kept, as in the ToggleController examples
assert.deepEqual(actionMappings[0].directive, { name: "TurnOn" });
assert.deepEqual(semantics().action("Open", "TurnOn", {}).actionMappings[0].directive, { name: "TurnOn", payload: {} });
assert.deepEqual(semanticsOf(ToggleController).parse(semantics().action("Open", "TurnOn")).actionMappings[0].directive, { name: "TurnOn" });
});
test("a mapping is checked against the directives and the property of the interface", () => {
const cases = [
[RangeController, semantics().action("Open", "SetRange", { rangeValue: 100 }),
'semantics.actionMappings[0].directive.name: expected a directive of the interface: SetRangeValue, AdjustRangeValue, got "SetRange"'],
[RangeController, semantics().action("Open", "SetRangeValue", { rangeValue: "100" }),
'semantics.actionMappings[0].directive.payload.rangeValue: expected a number, got "100"'],
[RangeController, semantics().action("Open", "SetRangeValue"),
"semantics.actionMappings[0].directive.payload.rangeValue: expected a number, got nothing"],
[RangeController, semantics().action("Lower", "AdjustRangeValue", { rangeValueDelta: -10 }),
"semantics.actionMappings[0].directive.payload.rangeValueDeltaDefault: expected true or false, got nothing"],
[RangeController, semantics().action("Shut", "SetRangeValue", { rangeValue: 0 }),
'semantics.actionMappings[0].actions[0]: expected a phrase of Alexa.Actions: Open, Close, Raise, Lower, got "Alexa.Actions.Shut"'],
[RangeController, semantics().state("Ajar", 50),
'semantics.stateMappings[0].states[0]: expected a state of Alexa.States: Open, Closed, Low, Empty, Full, Done, Stuck, got "Alexa.States.Ajar"'],
[RangeController, semantics().state("Closed", "OFF"), 'semantics.stateMappings[0].value: expected a number, got "OFF"'],
[RangeController, semantics().stateRange("Open", 100, 1), "semantics.stateMappings[0].range: the minimumValue 100 is above the maximumValue 1"],
[ToggleController, semantics().state("Open", "on"), 'semantics.stateMappings[0].value: expected ON | OFF, got "on"'],
[ToggleController, semantics().stateRange("Open", 1, 100), 'semantics.stateMappings[0].@type: expected StatesToValue, got "StatesToRange"'],
[ModeController, semantics().state("Closed", 0), "semantics.stateMappings[0].value: expected a string of 1 or more characters, got 0"],
[ToggleController, semantics(), "semantics: expected semantics() with at least one action or state, got {}"],
[ToggleController, "open", 'semantics: expected semantics() with at least one action or state, got "open"'],
[ToggleController, { actionMappings: [{ "@type": "ActionToDirective", actions: ["Alexa.Actions.Open"], directive: { name: "TurnOn" } }] },
'semantics.actionMappings[0].@type: expected "ActionsToDirective", got "ActionToDirective"'],
];
for (const [descriptor, input, message] of cases) assert.equal(refusal(descriptor, input), message);
});
test("the phrases and states of Alexa hunches are for a ToggleController", () => {
const eco = semantics().action("SetEcoOn", "TurnOn").action("SetEcoOff", "TurnOff").state("EcoOn", "ON").state("EcoOff", "OFF");
assert.deepEqual(semanticsOf(ToggleController).parse(eco), {
actionMappings: [
{ "@type": "ActionsToDirective", actions: ["Alexa.Actions.SetEcoOn"], directive: { name: "TurnOn" } },
{ "@type": "ActionsToDirective", actions: ["Alexa.Actions.SetEcoOff"], directive: { name: "TurnOff" } },
],
stateMappings: [
{ "@type": "StatesToValue", states: ["Alexa.States.EcoOn"], value: "ON" },
{ "@type": "StatesToValue", states: ["Alexa.States.EcoOff"], value: "OFF" },
],
});
assert.match(
refusal(RangeController, semantics().action("SetEcoOn", "SetRangeValue", { rangeValue: 20 })),
/^semantics\.actionMappings\[0\]\.actions\[0\]: expected a phrase of Alexa\.Actions: Open, Close, Raise, Lower, got "Alexa\.Actions\.SetEcoOn"$/
);
assert.match(refusal(ModeController, semantics().state("EcoOn", "Position.Up")), /expected a state of Alexa\.States: Open, Closed, Low, Empty, Full, Done, Stuck, got/);
});