discovery: generate capability JSON from the registry
A capability is a descriptor plus what the endpoint declares (device/Capability.ts), and its discovery object is
generated from the two. The new API is bridge.addDevice({ endpointId, name, categories, ... }) and
device.add(PowerController, options): both throw a DeclarationError that names the endpoint, the interface and
the instance (device/validate.ts), and leave the bridge and the device as they were. AlexaInterface is the same
Capability with the 1.x methods on it; it, ActionMapping and the enums moved to src/compat/, Device to src/device/.
What a 1.x caller can observe:
- every endpoint ends with { type: "AlexaInterface", interface: "Alexa", version: "3" } (alexa-interface.html);
new Alex2MQTT(..., { alexaInterface: false }) leaves it out
- the fields of a capability object come in the order of Amazon's examples; their content is unchanged
- addCapability() with a name that is not an interface throws (1.5.2 announced it with the version "UNKNOWN")
- ActionMapping takes the payload as an object; a JSON string is parsed (1.5.2 sent the string), any other throws
- what Alexa would reject in a 1.x declaration is not refused: device.check() lists it and the bridge logs each
line once, as "warning: ..." through the log hook, when it answers a discovery
- a device whose JSON cannot be built is left out of the answer and reported as an error event
- PowerController and EndpointHealth are the descriptors and keep ON/OFF and OK/UNREACHABLE; PowerState is new
Tests: six zoo devices declared the 1.x way give the JSON that Alexa accepted from 1.5.2 on 2026-09-28, plus the
Alexa capability. npm test: 85 pass (was 57) in 10-12 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:
parent
aa0ffd64ea
commit
c492ef74d1
90 changed files with 5539 additions and 1760 deletions
32
dist/cjs/ActionMapping.js
vendored
32
dist/cjs/ActionMapping.js
vendored
|
|
@ -1,32 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ActionMapping = exports.AlexaActions = void 0;
|
||||
var AlexaActions;
|
||||
(function (AlexaActions) {
|
||||
AlexaActions["Open"] = "Alexa.Actions.Open";
|
||||
AlexaActions["Close"] = "Alexa.Actions.Close";
|
||||
AlexaActions["Raise"] = "Alexa.Actions.Raise";
|
||||
AlexaActions["Lower"] = "Alexa.Actions.Lower";
|
||||
AlexaActions["SetEcoOn"] = "Alexa.Actions.SetEcoOn";
|
||||
AlexaActions["SetEcoOff"] = "Alexa.Actions.SetEcoOff";
|
||||
})(AlexaActions || (exports.AlexaActions = AlexaActions = {}));
|
||||
class ActionMapping {
|
||||
constructor(actions, directiveName, directivePayload) {
|
||||
this.type = "ActionsToDirective";
|
||||
this.actions = actions;
|
||||
this.directive = {
|
||||
name: directiveName,
|
||||
};
|
||||
if (directivePayload) {
|
||||
this.directive.payload = directivePayload;
|
||||
}
|
||||
}
|
||||
toJSON() {
|
||||
return {
|
||||
"@type": this.type,
|
||||
actions: this.actions,
|
||||
directive: this.directive,
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.ActionMapping = ActionMapping;
|
||||
83
dist/cjs/Alex2Node.js
vendored
83
dist/cjs/Alex2Node.js
vendored
|
|
@ -6,11 +6,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|||
exports.DEFAULT_HOST = void 0;
|
||||
// mqtt reaches Node as CommonJS: the default import works from both builds, a named one needs Node to detect it.
|
||||
const mqtt_1 = __importDefault(require("mqtt"));
|
||||
const Device_js_1 = __importDefault(require("./Device.js"));
|
||||
const Device_js_1 = __importDefault(require("./device/Device.js"));
|
||||
const validate_js_1 = require("./device/validate.js");
|
||||
const events_1 = require("events");
|
||||
const DisplayCategory_js_1 = require("./DisplayCategory.js");
|
||||
const AlexaInterface_js_1 = require("./AlexaInterface.js");
|
||||
const enums_js_1 = require("./compat/enums.js");
|
||||
const types_js_1 = require("./registry/types.js");
|
||||
exports.DEFAULT_HOST = "mqtt://Alex2MQTT.stormysdream.club:1883";
|
||||
// What addDevice() copies from the definition to the device
|
||||
const DESCRIBED = [
|
||||
"description", "manufacturerName", "manufacturer", "model", "serialNumber", "firmwareVersion", "softwareVersion",
|
||||
"customIdentifier", "cookie",
|
||||
];
|
||||
/**
|
||||
* The Alexa-to-MQTT bridge: one broker connection for a user's root topic, a set of registered devices, discovery and
|
||||
* directive dispatch.
|
||||
|
|
@ -34,6 +40,8 @@ class Alex2MQTT extends events_1.EventEmitter {
|
|||
this.debugLogging = debugLogging;
|
||||
this.client = null;
|
||||
this.devices = [];
|
||||
// The lines of check() that were logged. Discovery comes every few minutes: a line is logged once.
|
||||
this.logged = new Set();
|
||||
/** true while the broker connection is up. */
|
||||
this.connected = false;
|
||||
/** ISO time of the last discovery request answered, null before the first. */
|
||||
|
|
@ -90,12 +98,8 @@ class Alex2MQTT extends events_1.EventEmitter {
|
|||
this.log(`MQTT Message Received`, { topic, payload: message.toString() });
|
||||
if (topic == `${this.rootTopic}/discover`) {
|
||||
this.log("Discovery request received, getting device json...");
|
||||
const deviceArray = this.devices.map((device) => device.getJSON());
|
||||
const deviceArray = this.describeDevices();
|
||||
this.lastDiscoveryAt = new Date().toISOString();
|
||||
for (const device of this.devices) // a capability the library has no property list for goes out with supported: []
|
||||
for (const cap of device.getCapabilities())
|
||||
if (cap.getProps().length === 0 && cap.getType() !== AlexaInterface_js_1.AlexaInterfaceType.SCENE_CONTROLLER)
|
||||
this.log(`${device.endpointId}: no property list known for ${cap.getTypeString()}, discovery lists it with no supported properties`);
|
||||
this.client.publish(topic + "_r", JSON.stringify(deviceArray), (err) => {
|
||||
if (err) {
|
||||
this.fail(err);
|
||||
|
|
@ -136,6 +140,26 @@ class Alex2MQTT extends events_1.EventEmitter {
|
|||
}
|
||||
});
|
||||
}
|
||||
// The endpoint objects of a discovery answer. What check() says about a device is logged, each line once. A device
|
||||
// that cannot be described is left out and reported as an error: the others are still announced.
|
||||
describeDevices() {
|
||||
const endpoints = [];
|
||||
for (const device of this.devices) {
|
||||
try {
|
||||
endpoints.push(device.getJSON());
|
||||
for (const line of device.check()) {
|
||||
if (this.logged.has(line))
|
||||
continue;
|
||||
this.logged.add(line);
|
||||
this.log(`warning: ${line}`);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
this.fail(new Error(`${device.endpointId} is not in the discovery answer: ${err instanceof Error ? err.message : err}`));
|
||||
}
|
||||
}
|
||||
return endpoints;
|
||||
}
|
||||
/** Close the broker connection (resolves once closed). The devices stay registered; connect() again reuses them. */
|
||||
disconnect() {
|
||||
return new Promise((resolve) => {
|
||||
|
|
@ -147,6 +171,36 @@ class Alex2MQTT extends events_1.EventEmitter {
|
|||
c.end(true, {}, () => resolve());
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Declare a device:
|
||||
*
|
||||
* const blinds = bridge.addDevice({ endpointId: "bedroom-blinds", name: "Bedroom Blinds",
|
||||
* categories: ["INTERIOR_BLIND"], manufacturerName: "Acme", description: "Roller blind by Acme" });
|
||||
*
|
||||
* Throws a DeclarationError when Alexa would reject the endpoint (an endpointId with a slash, a name with
|
||||
* punctuation) or when the endpointId is registered already. Discovery lists Alexa.EndpointHealth for the device
|
||||
* unless endpointHealth is false.
|
||||
*/
|
||||
addDevice(definition) {
|
||||
if (!this.client) {
|
||||
throw new Error("Must call connect before creating devices");
|
||||
}
|
||||
const { endpointId, name, categories, endpointHealth, ...described } = definition;
|
||||
// Without categories the device would take LIGHT, the default of registerDevice: here it is a mistake
|
||||
const device = new Device_js_1.default(this.client, this.rootTopic, name, endpointId, (categories ?? []));
|
||||
for (const [field, value] of Object.entries(described)) {
|
||||
if (!DESCRIBED.includes(field))
|
||||
throw new types_js_1.DeclarationError({ endpointId }, `${field} is not a field of an endpoint`);
|
||||
if (value !== undefined)
|
||||
Object.assign(device, { [field]: value });
|
||||
}
|
||||
(0, validate_js_1.checkEndpoint)(device.getJSON());
|
||||
const existing = this.getDevice(endpointId);
|
||||
if (existing)
|
||||
throw new types_js_1.DeclarationError({ endpointId }, `is registered already, as "${existing.name}"`);
|
||||
this.register(device, endpointHealth !== false);
|
||||
return device;
|
||||
}
|
||||
registerDevice(name, endpointId, displayCategory) {
|
||||
if (!this.client) {
|
||||
throw new Error("Must call connect before creating devices");
|
||||
|
|
@ -161,15 +215,16 @@ class Alex2MQTT extends events_1.EventEmitter {
|
|||
return existing;
|
||||
}
|
||||
this.log(`Creating new device with endpoint: ${endpointId}`);
|
||||
const normalizedCategory = displayCategory === null
|
||||
? [DisplayCategory_js_1.DisplayCategory.LIGHT]
|
||||
: Array.isArray(displayCategory)
|
||||
? displayCategory
|
||||
: [displayCategory || DisplayCategory_js_1.DisplayCategory.LIGHT];
|
||||
const normalizedCategory = Array.isArray(displayCategory) ? displayCategory : [displayCategory || enums_js_1.DisplayCategory.LIGHT];
|
||||
const device = new Device_js_1.default(this.client, this.rootTopic, name, endpointId, normalizedCategory);
|
||||
this.register(device, false);
|
||||
return device;
|
||||
}
|
||||
register(device, endpointHealth) {
|
||||
device.alexaInterface = this.options.alexaInterface !== false;
|
||||
device.endpointHealth = endpointHealth;
|
||||
device.onPublishError = (err) => this.fail(err); // a failed publish is an "error" event (when listened to), never a rejected send()
|
||||
this.devices.push(device);
|
||||
return device;
|
||||
}
|
||||
/** Forget a device (its listeners with it). Returns false when there was none. */
|
||||
unregisterDevice(endpointId) {
|
||||
|
|
|
|||
32
dist/cjs/AlexaStatusMessage.js
vendored
32
dist/cjs/AlexaStatusMessage.js
vendored
|
|
@ -1,13 +1,8 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AlexaStatusMessage = exports.TemperatureSensorScale = exports.PowerController = exports.ThermostatMode = exports.EndpointHealth = void 0;
|
||||
exports.AlexaStatusMessage = exports.TemperatureSensorScale = exports.ThermostatMode = void 0;
|
||||
const crypto_1 = require("crypto");
|
||||
const AlexaInterface_js_1 = require("./AlexaInterface.js");
|
||||
var EndpointHealth;
|
||||
(function (EndpointHealth) {
|
||||
EndpointHealth["OK"] = "OK";
|
||||
EndpointHealth["UNREACHABLE"] = "UNREACHABLE";
|
||||
})(EndpointHealth || (exports.EndpointHealth = EndpointHealth = {}));
|
||||
const enums_js_1 = require("./compat/enums.js");
|
||||
var ThermostatMode;
|
||||
(function (ThermostatMode) {
|
||||
ThermostatMode["OFF"] = "OFF";
|
||||
|
|
@ -17,11 +12,6 @@ var ThermostatMode;
|
|||
ThermostatMode["ECO"] = "ECO";
|
||||
ThermostatMode["CUSTOM"] = "CUSTOM";
|
||||
})(ThermostatMode || (exports.ThermostatMode = ThermostatMode = {}));
|
||||
var PowerController;
|
||||
(function (PowerController) {
|
||||
PowerController["ON"] = "ON";
|
||||
PowerController["OFF"] = "OFF";
|
||||
})(PowerController || (exports.PowerController = PowerController = {}));
|
||||
var TemperatureSensorScale;
|
||||
(function (TemperatureSensorScale) {
|
||||
TemperatureSensorScale["CELSIUS"] = "CELSIUS";
|
||||
|
|
@ -102,10 +92,10 @@ class AlexaStatusMessage {
|
|||
return { context: this.isDeferred ? null : this.context, event: this.event };
|
||||
}
|
||||
addModeControllerProp(instance, value, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.MODE_CONTROLLER, "mode", value, uncertaintyInMs, instance);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.MODE_CONTROLLER, "mode", value, uncertaintyInMs, instance);
|
||||
}
|
||||
addThermostatModeProp(mode, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.THERMOSTAT_CONTROLLER, "thermostatMode", mode, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.THERMOSTAT_CONTROLLER, "thermostatMode", mode, uncertaintyInMs);
|
||||
}
|
||||
addEstimatedDeferralTime(seconds) {
|
||||
if (this.isDeferred) {
|
||||
|
|
@ -125,14 +115,14 @@ class AlexaStatusMessage {
|
|||
: value,
|
||||
scale: "CELSIUS",
|
||||
};
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.THERMOSTAT_CONTROLLER, name, tempValue, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.THERMOSTAT_CONTROLLER, name, tempValue, uncertaintyInMs);
|
||||
}
|
||||
/** Alexa.EndpointHealth connectivity: EndpointHealth.OK / UNREACHABLE (the plain strings "OK" / "UNREACHABLE" are accepted too). */
|
||||
addHealthProp(health, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.ENDPOINT_HEALTH, "connectivity", { value: health }, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.ENDPOINT_HEALTH, "connectivity", { value: health }, uncertaintyInMs);
|
||||
}
|
||||
addPowerControllerProp(power, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.POWER_CONTROLLER, "powerState", power, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.POWER_CONTROLLER, "powerState", power, uncertaintyInMs);
|
||||
}
|
||||
addTemperatureSensorProp(scale, value, uncertaintyInMs = 0) {
|
||||
const tempValue = {
|
||||
|
|
@ -141,16 +131,16 @@ class AlexaStatusMessage {
|
|||
: value,
|
||||
scale: "CELSIUS",
|
||||
};
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.TEMPERATURE_SENSOR, "temperature", tempValue, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.TEMPERATURE_SENSOR, "temperature", tempValue, uncertaintyInMs);
|
||||
}
|
||||
addBrightnessControllerProp(brightness, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.BRIGHTNESS_CONTROLLER, "brightness", brightness, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.BRIGHTNESS_CONTROLLER, "brightness", brightness, uncertaintyInMs);
|
||||
}
|
||||
addColorTemperatureControllerProp(colorTemp, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.COLOR_TEMPERATURE_CONTROLLER, "colorTemperatureInKelvin", colorTemp, uncertaintyInMs);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.COLOR_TEMPERATURE_CONTROLLER, "colorTemperatureInKelvin", colorTemp, uncertaintyInMs);
|
||||
}
|
||||
addToggleControllerProp(state, instance, uncertaintyInMs = 0) {
|
||||
return this.addProperty(AlexaInterface_js_1.AlexaInterfaceType.TOGGLE_CONTROLLER, "toggleState", state, uncertaintyInMs, instance);
|
||||
return this.addProperty(enums_js_1.AlexaInterfaceType.TOGGLE_CONTROLLER, "toggleState", state, uncertaintyInMs, instance);
|
||||
}
|
||||
addContextProp(prop) {
|
||||
this.context.properties.push(prop);
|
||||
|
|
|
|||
145
dist/cjs/Device.js
vendored
145
dist/cjs/Device.js
vendored
|
|
@ -1,145 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const AlexaInterface_js_1 = require("./AlexaInterface.js");
|
||||
const DisplayCategory_js_1 = require("./DisplayCategory.js");
|
||||
const events_1 = require("events");
|
||||
const crypto_1 = require("crypto");
|
||||
const AlexaStatusMessage_js_1 = require("./AlexaStatusMessage.js");
|
||||
const AlexaErrorResponse_js_1 = require("./AlexaErrorResponse.js");
|
||||
class Device extends events_1.EventEmitter {
|
||||
constructor(mqttClient, rootTopic, name, endpointId, displayCategory, description = "Alexa to Node.js bridge", manufacturerName = "Alex2Node", manufacturer = "Alex2Node", model = "Alex2Node_v1.0.0") {
|
||||
super();
|
||||
this.mqttClient = mqttClient;
|
||||
this.rootTopic = rootTopic;
|
||||
this.name = name;
|
||||
this.endpointId = endpointId;
|
||||
this.displayCategory = displayCategory;
|
||||
this.description = description;
|
||||
this.manufacturerName = manufacturerName;
|
||||
this.manufacturer = manufacturer;
|
||||
this.model = model;
|
||||
this.softwareVersion = "1.0.0";
|
||||
this.capabilities = [];
|
||||
}
|
||||
/** Internal (1.5.2): Alex2MQTT.connect() re-binds every registered device to its new broker client after a disconnect(). */
|
||||
setMqttClient(client) {
|
||||
this.mqttClient = client;
|
||||
}
|
||||
getName() {
|
||||
return this.name;
|
||||
}
|
||||
setName(name) {
|
||||
this.name = name;
|
||||
}
|
||||
getEndpointId() {
|
||||
return this.endpointId;
|
||||
}
|
||||
setDisplayCategory(category) {
|
||||
this.displayCategory = Array.isArray(category) ? category : [category];
|
||||
}
|
||||
getDisplayCategory() {
|
||||
return this.displayCategory || [DisplayCategory_js_1.DisplayCategory.LIGHT];
|
||||
}
|
||||
setDescription(description) {
|
||||
this.description = description;
|
||||
}
|
||||
getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
getErrorMessage(correlationToken) {
|
||||
const msg = new AlexaErrorResponse_js_1.AlexaErrorResponse(correlationToken, this.rootTopic, this.endpointId, this.mqttClient);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
getStatusMessage(correlationToken, isResponse = false, isDeferred = false) {
|
||||
const msg = new AlexaStatusMessage_js_1.AlexaStatusMessage(correlationToken, this.rootTopic, this.endpointId, this.mqttClient, isResponse, isDeferred);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
/**
|
||||
* A proactive Alexa.ChangeReport (1.5.1): add the changed properties (the default target), optionally
|
||||
* .unchanged() then the others, and .send() - it goes to <root>/changeReport, which Alex2MQTT forwards to the Alexa
|
||||
* event gateway with the user's token. Alexa only accepts it for capabilities registered with proactivelyReported.
|
||||
*/
|
||||
getChangeReport(cause = "PHYSICAL_INTERACTION") {
|
||||
const msg = new AlexaStatusMessage_js_1.AlexaStatusMessage("", this.rootTopic, this.endpointId, this.mqttClient, false, false, cause);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
/**
|
||||
* Alexa.SceneController: answer an Activate / Deactivate directive with ActivationStarted / DeactivationStarted
|
||||
* (1.5.1). Resolves with the topic published to, or "" when the publish failed (never rejects, 1.5.2).
|
||||
*/
|
||||
sendSceneResponse(correlationToken, activated, cause = "VOICE_INTERACTION", sendAsync = false) {
|
||||
const payload = {
|
||||
context: {},
|
||||
event: {
|
||||
header: { namespace: "Alexa.SceneController", name: activated ? "ActivationStarted" : "DeactivationStarted", messageId: (0, crypto_1.randomUUID)(), correlationToken, payloadVersion: "3" },
|
||||
endpoint: { endpointId: this.endpointId },
|
||||
payload: { cause: { type: cause }, timestamp: new Date().toISOString() },
|
||||
},
|
||||
};
|
||||
const topic = `${this.rootTopic}/${this.endpointId}/${sendAsync ? "deferredResponse" : "alexaResponce"}`;
|
||||
return new Promise((resolve) => {
|
||||
this.mqttClient.publish(topic, JSON.stringify(payload), (err) => {
|
||||
if (!err)
|
||||
return resolve(topic);
|
||||
if (this.onPublishError)
|
||||
this.onPublishError(err); // -> the bridge's "error" event (when somebody listens)
|
||||
resolve(""); // 1.5.1 rejected here, and an un-caught send() then killed the host on any broker hiccup
|
||||
});
|
||||
});
|
||||
}
|
||||
getCapabilities() {
|
||||
return this.capabilities.slice();
|
||||
}
|
||||
setManufacturerName(name) {
|
||||
this.manufacturerName = name;
|
||||
}
|
||||
getManufacturerName() {
|
||||
return this.manufacturerName;
|
||||
}
|
||||
setManufacturer(manufacturer) {
|
||||
this.manufacturer = manufacturer;
|
||||
}
|
||||
getManufacturer() {
|
||||
return this.manufacturer;
|
||||
}
|
||||
setModel(model) {
|
||||
this.model = model;
|
||||
}
|
||||
getModel() {
|
||||
return this.model;
|
||||
}
|
||||
getSoftwareVersion() {
|
||||
return this.softwareVersion;
|
||||
}
|
||||
/** Add a capability. 1.5.1: options.retrievable / proactivelyReported / instance (a change report needs proactivelyReported). */
|
||||
addCapability(type, options = {}) {
|
||||
const newCapability = new AlexaInterface_js_1.AlexaInterface(type, options.retrievable ?? true, options.proactivelyReported ?? false, options.instance ?? "");
|
||||
this.capabilities.push(newCapability);
|
||||
// console.log(
|
||||
// `Created new interface with type: ${newCapability.getTypeString()}`
|
||||
// );
|
||||
return newCapability;
|
||||
}
|
||||
getJSON() {
|
||||
return {
|
||||
endpointId: this.endpointId,
|
||||
friendlyName: this.name,
|
||||
description: this.description,
|
||||
manufacturerName: this.manufacturerName,
|
||||
displayCategories: this.getDisplayCategory(),
|
||||
additionalAttributes: {
|
||||
manufacturer: this.manufacturer,
|
||||
model: this.model,
|
||||
serialNumber: "Alex2Node",
|
||||
firmwareVersion: "1.0.0",
|
||||
softwareVersion: this.softwareVersion,
|
||||
customIdentifier: "Alex2Node",
|
||||
},
|
||||
capabilities: this.capabilities.map((cap) => cap.getJSON()),
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.default = Device;
|
||||
64
dist/cjs/DisplayCategory.js
vendored
64
dist/cjs/DisplayCategory.js
vendored
|
|
@ -1,64 +0,0 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DisplayCategory = void 0;
|
||||
var DisplayCategory;
|
||||
(function (DisplayCategory) {
|
||||
DisplayCategory["ACTIVITY_TRIGGER"] = "ACTIVITY_TRIGGER";
|
||||
DisplayCategory["AIR_CONDITIONER"] = "AIR_CONDITIONER";
|
||||
DisplayCategory["AIR_FRESHENER"] = "AIR_FRESHENER";
|
||||
DisplayCategory["AIR_PURIFIER"] = "AIR_PURIFIER";
|
||||
DisplayCategory["AIR_QUALITY_MONITOR"] = "AIR_QUALITY_MONITOR";
|
||||
DisplayCategory["ALEXA_VOICE_ENABLED"] = "ALEXA_VOICE_ENABLED";
|
||||
DisplayCategory["AUTO_ACCESSORY"] = "AUTO_ACCESSORY";
|
||||
DisplayCategory["BLUETOOTH_SPEAKER"] = "BLUETOOTH_SPEAKER";
|
||||
DisplayCategory["CAMERA"] = "CAMERA";
|
||||
DisplayCategory["CHRISTMAS_TREE"] = "CHRISTMAS_TREE";
|
||||
DisplayCategory["COFFEE_MAKER"] = "COFFEE_MAKER";
|
||||
DisplayCategory["COMPUTER"] = "COMPUTER";
|
||||
DisplayCategory["CONTACT_SENSOR"] = "CONTACT_SENSOR";
|
||||
DisplayCategory["DISHWASHER"] = "DISHWASHER";
|
||||
DisplayCategory["DOOR"] = "DOOR";
|
||||
DisplayCategory["DOORBELL"] = "DOORBELL";
|
||||
DisplayCategory["DRYER"] = "DRYER";
|
||||
DisplayCategory["EXTERIOR_BLIND"] = "EXTERIOR_BLIND";
|
||||
DisplayCategory["FAN"] = "FAN";
|
||||
DisplayCategory["GAME_CONSOLE"] = "GAME_CONSOLE";
|
||||
DisplayCategory["GARAGE_DOOR"] = "GARAGE_DOOR";
|
||||
DisplayCategory["HEADPHONES"] = "HEADPHONES";
|
||||
DisplayCategory["HUB"] = "HUB";
|
||||
DisplayCategory["INTERIOR_BLIND"] = "INTERIOR_BLIND";
|
||||
DisplayCategory["LAPTOP"] = "LAPTOP";
|
||||
DisplayCategory["LIGHT"] = "LIGHT";
|
||||
DisplayCategory["MICROWAVE"] = "MICROWAVE";
|
||||
DisplayCategory["MOBILE_PHONE"] = "MOBILE_PHONE";
|
||||
DisplayCategory["MOTION_SENSOR"] = "MOTION_SENSOR";
|
||||
DisplayCategory["MUSIC_SYSTEM"] = "MUSIC_SYSTEM";
|
||||
DisplayCategory["NETWORK_HARDWARE"] = "NETWORK_HARDWARE";
|
||||
DisplayCategory["OTHER"] = "OTHER";
|
||||
DisplayCategory["OVEN"] = "OVEN";
|
||||
DisplayCategory["PHONE"] = "PHONE";
|
||||
DisplayCategory["PRINTER"] = "PRINTER";
|
||||
DisplayCategory["REMOTE"] = "REMOTE";
|
||||
DisplayCategory["ROUTER"] = "ROUTER";
|
||||
DisplayCategory["SCENE_TRIGGER"] = "SCENE_TRIGGER";
|
||||
DisplayCategory["SCREEN"] = "SCREEN";
|
||||
DisplayCategory["SECURITY_PANEL"] = "SECURITY_PANEL";
|
||||
DisplayCategory["SECURITY_SYSTEM"] = "SECURITY_SYSTEM";
|
||||
DisplayCategory["SLOW_COOKER"] = "SLOW_COOKER";
|
||||
DisplayCategory["SMARTLOCK"] = "SMARTLOCK";
|
||||
DisplayCategory["SMARTPLUG"] = "SMARTPLUG";
|
||||
DisplayCategory["SPEAKER"] = "SPEAKER";
|
||||
DisplayCategory["STREAMING_DEVICE"] = "STREAMING_DEVICE";
|
||||
DisplayCategory["SWITCH"] = "SWITCH";
|
||||
DisplayCategory["TABLET"] = "TABLET";
|
||||
DisplayCategory["TEMPERATURE_SENSOR"] = "TEMPERATURE_SENSOR";
|
||||
DisplayCategory["THERMOSTAT"] = "THERMOSTAT";
|
||||
DisplayCategory["TV"] = "TV";
|
||||
DisplayCategory["VACUUM_CLEANER"] = "VACUUM_CLEANER";
|
||||
DisplayCategory["VACUUM"] = "VACUUM";
|
||||
/** Not on the list of display categories any more; kept for 1.x callers. */
|
||||
DisplayCategory["VEHICLE"] = "VEHICLE";
|
||||
DisplayCategory["WASHER"] = "WASHER";
|
||||
DisplayCategory["WATER_HEATER"] = "WATER_HEATER";
|
||||
DisplayCategory["WEARABLE"] = "WEARABLE";
|
||||
})(DisplayCategory || (exports.DisplayCategory = DisplayCategory = {}));
|
||||
49
dist/cjs/compat/ActionMapping.js
vendored
Normal file
49
dist/cjs/compat/ActionMapping.js
vendored
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ActionMapping = void 0;
|
||||
const types_js_1 = require("../registry/types.js");
|
||||
/**
|
||||
* A semantics action mapping of 1.x: the phrases "open", "close", "raise", "lower" for one directive of the
|
||||
* capability it is added to.
|
||||
*
|
||||
* toggle.addActionMapping(new ActionMapping([AlexaActions.Close], "TurnOff"));
|
||||
* lift.addActionMapping(new ActionMapping([AlexaActions.Open], "SetRangeValue", { rangeValue: 100 }));
|
||||
*/
|
||||
class ActionMapping {
|
||||
/**
|
||||
* directivePayload is the payload object of the directive (alexa-discovery-objects.html, "ActionMappings object").
|
||||
* 1.x took a string and put it into discovery as one. A string that holds a JSON object is parsed; any other
|
||||
* string throws a DeclarationError.
|
||||
*/
|
||||
constructor(actions, directiveName, directivePayload) {
|
||||
this.type = "ActionsToDirective";
|
||||
this.actions = actions;
|
||||
this.directive = { name: directiveName };
|
||||
if (typeof directivePayload === "string") {
|
||||
if (directivePayload === "")
|
||||
return;
|
||||
this.directive.payload = objectIn(directivePayload, directiveName);
|
||||
this.deprecation = `the payload of the action mapping for ${directiveName} is a JSON string, pass the object`;
|
||||
}
|
||||
else if (directivePayload) {
|
||||
this.directive.payload = directivePayload;
|
||||
}
|
||||
}
|
||||
toJSON() {
|
||||
return { "@type": this.type, actions: this.actions, directive: this.directive };
|
||||
}
|
||||
}
|
||||
exports.ActionMapping = ActionMapping;
|
||||
function objectIn(text, directiveName) {
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(text);
|
||||
}
|
||||
catch {
|
||||
value = undefined;
|
||||
}
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||
throw new types_js_1.DeclarationError({}, `the payload of the action mapping for ${directiveName} is an object, got the string ${JSON.stringify(text)}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
61
dist/cjs/compat/AlexaInterface.js
vendored
Normal file
61
dist/cjs/compat/AlexaInterface.js
vendored
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AlexaInterface = void 0;
|
||||
const Capability_js_1 = require("../device/Capability.js");
|
||||
const index_js_1 = require("../registry/index.js");
|
||||
const resources_js_1 = require("../registry/resources.js");
|
||||
/**
|
||||
* A capability as 1.x declares it: device.addCapability(type, options), then the add and set methods below. It is a
|
||||
* Capability, so what the methods set reaches discovery the same way as the options of device.add(). Nothing is
|
||||
* refused here except an interface name the registry does not have: what Alexa would reject is logged by the bridge
|
||||
* when it answers a discovery.
|
||||
*/
|
||||
class AlexaInterface extends Capability_js_1.Capability {
|
||||
constructor(type, retrievable = true, proactivelyReported = false, instance = "") {
|
||||
super(index_js_1.registry.get(type), { retrievable, proactivelyReported, instance, options: {} });
|
||||
}
|
||||
/** The namespace of the interface, which is the value of its AlexaInterfaceType member. */
|
||||
get type() {
|
||||
return this.descriptor.namespace;
|
||||
}
|
||||
addActionMapping(mapping) {
|
||||
var _a;
|
||||
const semantics = ((_a = this.options).semantics ?? (_a.semantics = {}));
|
||||
(semantics.actionMappings ?? (semantics.actionMappings = [])).push(mapping.toJSON());
|
||||
if (mapping.deprecation)
|
||||
this.notes.push(mapping.deprecation);
|
||||
}
|
||||
addFriendlyName(name, locale) {
|
||||
this.friendlyNames.push((0, resources_js_1.text)(name, locale));
|
||||
}
|
||||
/** The modes of a ModeController, as { value, modeResources } objects. */
|
||||
addSupportedModes(modes) {
|
||||
this.options.supportedModes = modes;
|
||||
}
|
||||
setInstance(name) {
|
||||
this.instance = name;
|
||||
}
|
||||
getType() {
|
||||
return this.type;
|
||||
}
|
||||
/** @deprecated The same as getType(). */
|
||||
getTypeString() {
|
||||
return this.type;
|
||||
}
|
||||
/** @deprecated Read descriptor.version. */
|
||||
getVersion() {
|
||||
return this.descriptor.version;
|
||||
}
|
||||
/** @deprecated Read the keys of descriptor.properties. */
|
||||
getProps() {
|
||||
return Object.keys(this.descriptor.properties);
|
||||
}
|
||||
getJSON() {
|
||||
return super.toJSON();
|
||||
}
|
||||
// 1.x callers corrected the discovery JSON by replacing getJSON on the object: discovery goes through it
|
||||
toJSON() {
|
||||
return this.getJSON();
|
||||
}
|
||||
}
|
||||
exports.AlexaInterface = AlexaInterface;
|
||||
|
|
@ -1,7 +1,10 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.AlexaInterface = exports.AlexaInterfaceType = void 0;
|
||||
const index_js_1 = require("./registry/index.js");
|
||||
exports.EndpointHealth = exports.PowerController = exports.PowerState = exports.AlexaActions = exports.DisplayCategory = exports.AlexaInterfaceType = void 0;
|
||||
// The enums of 1.x, under their 1.x names.
|
||||
const EndpointHealth_js_1 = require("../registry/interfaces/EndpointHealth.js");
|
||||
const PowerController_js_1 = require("../registry/interfaces/PowerController.js");
|
||||
/** Every interface name of 1.x. registry.get() takes a member as it takes the namespace, which is its value. */
|
||||
var AlexaInterfaceType;
|
||||
(function (AlexaInterfaceType) {
|
||||
AlexaInterfaceType["APPLICATION_STATE_REPORTER"] = "Alexa.ApplicationStateReporter";
|
||||
|
|
@ -73,97 +76,88 @@ var AlexaInterfaceType;
|
|||
AlexaInterfaceType["USER_PREFERENCE"] = "Alexa.UserPreference";
|
||||
AlexaInterfaceType["VIDEO_RECORDER"] = "Alexa.VideoRecorder";
|
||||
AlexaInterfaceType["WAKE_ON_LAN_CONTROLLER"] = "Alexa.WakeOnLANController";
|
||||
/** Not an interface: declaring it throws a DeclarationError. Kept because 1.x had it. */
|
||||
AlexaInterfaceType["UNKNOWN"] = "UNKNOWN";
|
||||
})(AlexaInterfaceType || (exports.AlexaInterfaceType = AlexaInterfaceType = {}));
|
||||
class AlexaInterface {
|
||||
constructor(type, retrievable = true, proactivelyReported = false, instance = "") {
|
||||
this.type = type;
|
||||
this.retrievable = retrievable;
|
||||
this.proactivelyReported = proactivelyReported;
|
||||
this.instance = instance;
|
||||
this.friendlyNames = [];
|
||||
this.actionMappings = [];
|
||||
this.supportedModes = [];
|
||||
}
|
||||
addActionMapping(mapping) {
|
||||
this.actionMappings.push(mapping);
|
||||
}
|
||||
addFriendlyName(name, locale) {
|
||||
this.friendlyNames.push({ text: name, locale });
|
||||
}
|
||||
/** The modes of a ModeController: { value, modeResources } objects as Alexa wants them (plain strings pass through as given). */
|
||||
addSupportedModes(modes) {
|
||||
this.supportedModes = modes;
|
||||
}
|
||||
setInstance(name) {
|
||||
this.instance = name;
|
||||
}
|
||||
getType() {
|
||||
return this.type;
|
||||
}
|
||||
getTypeString() {
|
||||
return this.type;
|
||||
}
|
||||
/** The version of the interface, from its descriptor. "UNKNOWN" for a name the registry does not have. */
|
||||
getVersion() {
|
||||
return index_js_1.registry.has(this.type) ? index_js_1.registry.get(this.type).version : "UNKNOWN";
|
||||
}
|
||||
/** The names of the properties the interface reports, from its descriptor. */
|
||||
getProps() {
|
||||
return index_js_1.registry.has(this.type) ? Object.keys(index_js_1.registry.get(this.type).properties) : [];
|
||||
}
|
||||
getJSON() {
|
||||
const doc = {
|
||||
interface: this.getTypeString(),
|
||||
version: this.getVersion(),
|
||||
type: "AlexaInterface",
|
||||
properties: {
|
||||
retrievable: this.retrievable,
|
||||
proactivelyReported: this.proactivelyReported,
|
||||
supported: this.getProps().map(name => ({ name })),
|
||||
},
|
||||
};
|
||||
if (this.type == AlexaInterfaceType.SCENE_CONTROLLER) {
|
||||
// Alexa.SceneController v3 carries no properties block: supportsDeactivation + proactivelyReported at the top level
|
||||
delete doc.properties;
|
||||
doc.supportsDeactivation = true;
|
||||
doc.proactivelyReported = this.proactivelyReported;
|
||||
}
|
||||
else if (this.type == AlexaInterfaceType.THERMOSTAT_CONTROLLER) {
|
||||
doc.configuration = {
|
||||
"supportedModes": ["HEAT", "COOL", "AUTO", "OFF"],
|
||||
"supportsScheduling": false
|
||||
};
|
||||
}
|
||||
else if (this.supportedModes.length > 0) {
|
||||
doc["configuration"] = {
|
||||
ordered: true,
|
||||
supportedModes: this.supportedModes,
|
||||
};
|
||||
}
|
||||
if (this.instance) {
|
||||
doc.instance = this.instance;
|
||||
}
|
||||
if (this.friendlyNames.length > 0) {
|
||||
const capabilityResources = doc["capabilityResources"] || {};
|
||||
const friendlyNamesArray = capabilityResources["friendlyNames"] || [];
|
||||
this.friendlyNames.forEach((fn) => {
|
||||
const friendlyNameObj = { "@type": "text" };
|
||||
friendlyNameObj["value"] = {
|
||||
text: fn.text,
|
||||
locale: fn.locale,
|
||||
};
|
||||
friendlyNamesArray.push(friendlyNameObj);
|
||||
});
|
||||
capabilityResources.friendlyNames = friendlyNamesArray;
|
||||
doc["capabilityResources"] = capabilityResources;
|
||||
}
|
||||
if (this.actionMappings.length > 0) {
|
||||
doc.semantics = {
|
||||
actionMappings: this.actionMappings.map((am) => am.toJSON()),
|
||||
};
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
}
|
||||
exports.AlexaInterface = AlexaInterface;
|
||||
var DisplayCategory;
|
||||
(function (DisplayCategory) {
|
||||
DisplayCategory["ACTIVITY_TRIGGER"] = "ACTIVITY_TRIGGER";
|
||||
DisplayCategory["AIR_CONDITIONER"] = "AIR_CONDITIONER";
|
||||
DisplayCategory["AIR_FRESHENER"] = "AIR_FRESHENER";
|
||||
DisplayCategory["AIR_PURIFIER"] = "AIR_PURIFIER";
|
||||
DisplayCategory["AIR_QUALITY_MONITOR"] = "AIR_QUALITY_MONITOR";
|
||||
DisplayCategory["ALEXA_VOICE_ENABLED"] = "ALEXA_VOICE_ENABLED";
|
||||
DisplayCategory["AUTO_ACCESSORY"] = "AUTO_ACCESSORY";
|
||||
DisplayCategory["BLUETOOTH_SPEAKER"] = "BLUETOOTH_SPEAKER";
|
||||
DisplayCategory["CAMERA"] = "CAMERA";
|
||||
DisplayCategory["CHRISTMAS_TREE"] = "CHRISTMAS_TREE";
|
||||
DisplayCategory["COFFEE_MAKER"] = "COFFEE_MAKER";
|
||||
DisplayCategory["COMPUTER"] = "COMPUTER";
|
||||
DisplayCategory["CONTACT_SENSOR"] = "CONTACT_SENSOR";
|
||||
DisplayCategory["DISHWASHER"] = "DISHWASHER";
|
||||
DisplayCategory["DOOR"] = "DOOR";
|
||||
DisplayCategory["DOORBELL"] = "DOORBELL";
|
||||
DisplayCategory["DRYER"] = "DRYER";
|
||||
DisplayCategory["EXTERIOR_BLIND"] = "EXTERIOR_BLIND";
|
||||
DisplayCategory["FAN"] = "FAN";
|
||||
DisplayCategory["GAME_CONSOLE"] = "GAME_CONSOLE";
|
||||
DisplayCategory["GARAGE_DOOR"] = "GARAGE_DOOR";
|
||||
DisplayCategory["HEADPHONES"] = "HEADPHONES";
|
||||
DisplayCategory["HUB"] = "HUB";
|
||||
DisplayCategory["INTERIOR_BLIND"] = "INTERIOR_BLIND";
|
||||
DisplayCategory["LAPTOP"] = "LAPTOP";
|
||||
DisplayCategory["LIGHT"] = "LIGHT";
|
||||
DisplayCategory["MICROWAVE"] = "MICROWAVE";
|
||||
DisplayCategory["MOBILE_PHONE"] = "MOBILE_PHONE";
|
||||
DisplayCategory["MOTION_SENSOR"] = "MOTION_SENSOR";
|
||||
DisplayCategory["MUSIC_SYSTEM"] = "MUSIC_SYSTEM";
|
||||
DisplayCategory["NETWORK_HARDWARE"] = "NETWORK_HARDWARE";
|
||||
DisplayCategory["OTHER"] = "OTHER";
|
||||
DisplayCategory["OVEN"] = "OVEN";
|
||||
DisplayCategory["PHONE"] = "PHONE";
|
||||
DisplayCategory["PRINTER"] = "PRINTER";
|
||||
DisplayCategory["REMOTE"] = "REMOTE";
|
||||
DisplayCategory["ROUTER"] = "ROUTER";
|
||||
DisplayCategory["SCENE_TRIGGER"] = "SCENE_TRIGGER";
|
||||
DisplayCategory["SCREEN"] = "SCREEN";
|
||||
DisplayCategory["SECURITY_PANEL"] = "SECURITY_PANEL";
|
||||
DisplayCategory["SECURITY_SYSTEM"] = "SECURITY_SYSTEM";
|
||||
DisplayCategory["SLOW_COOKER"] = "SLOW_COOKER";
|
||||
DisplayCategory["SMARTLOCK"] = "SMARTLOCK";
|
||||
DisplayCategory["SMARTPLUG"] = "SMARTPLUG";
|
||||
DisplayCategory["SPEAKER"] = "SPEAKER";
|
||||
DisplayCategory["STREAMING_DEVICE"] = "STREAMING_DEVICE";
|
||||
DisplayCategory["SWITCH"] = "SWITCH";
|
||||
DisplayCategory["TABLET"] = "TABLET";
|
||||
DisplayCategory["TEMPERATURE_SENSOR"] = "TEMPERATURE_SENSOR";
|
||||
DisplayCategory["THERMOSTAT"] = "THERMOSTAT";
|
||||
DisplayCategory["TV"] = "TV";
|
||||
DisplayCategory["VACUUM_CLEANER"] = "VACUUM_CLEANER";
|
||||
DisplayCategory["VACUUM"] = "VACUUM";
|
||||
/** Not on the list of display categories any more; kept for 1.x callers. */
|
||||
DisplayCategory["VEHICLE"] = "VEHICLE";
|
||||
DisplayCategory["WASHER"] = "WASHER";
|
||||
DisplayCategory["WATER_HEATER"] = "WATER_HEATER";
|
||||
DisplayCategory["WEARABLE"] = "WEARABLE";
|
||||
})(DisplayCategory || (exports.DisplayCategory = DisplayCategory = {}));
|
||||
var AlexaActions;
|
||||
(function (AlexaActions) {
|
||||
AlexaActions["Open"] = "Alexa.Actions.Open";
|
||||
AlexaActions["Close"] = "Alexa.Actions.Close";
|
||||
AlexaActions["Raise"] = "Alexa.Actions.Raise";
|
||||
AlexaActions["Lower"] = "Alexa.Actions.Lower";
|
||||
AlexaActions["SetEcoOn"] = "Alexa.Actions.SetEcoOn";
|
||||
AlexaActions["SetEcoOff"] = "Alexa.Actions.SetEcoOff";
|
||||
})(AlexaActions || (exports.AlexaActions = AlexaActions = {}));
|
||||
/** The values of powerState and toggleState. */
|
||||
exports.PowerState = { ON: "ON", OFF: "OFF" };
|
||||
const Connectivity = { OK: "OK", UNREACHABLE: "UNREACHABLE" };
|
||||
// PowerController and EndpointHealth were enums in 1.x and are the names of two interfaces. One export serves both:
|
||||
// the descriptor, which also has the members of the enum, and a type of the same name for the values.
|
||||
/**
|
||||
* The Alexa.PowerController interface, for device.add(). PowerController.ON and PowerController.OFF are the 1.x enum
|
||||
* of power states and stay until 3.0: PowerState has the same two members.
|
||||
*/
|
||||
exports.PowerController = Object.assign(PowerController_js_1.PowerController, exports.PowerState);
|
||||
/** The Alexa.EndpointHealth interface, for device.add(). EndpointHealth.OK and EndpointHealth.UNREACHABLE are the 1.x enum of connectivity values. */
|
||||
exports.EndpointHealth = Object.assign(EndpointHealth_js_1.EndpointHealth, Connectivity);
|
||||
67
dist/cjs/device/Capability.js
vendored
Normal file
67
dist/cjs/device/Capability.js
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Capability = exports.commonOptions = void 0;
|
||||
const schema_js_1 = require("../registry/schema.js");
|
||||
/** The same as a schema. The friendly names are checked with the instance, by the rules of the interface. */
|
||||
exports.commonOptions = schema_js_1.s.object({
|
||||
instance: schema_js_1.s.optional(schema_js_1.s.string()),
|
||||
friendlyNames: schema_js_1.s.optional(schema_js_1.s.array(schema_js_1.s.unknown())),
|
||||
retrievable: schema_js_1.s.optional(schema_js_1.s.boolean()),
|
||||
proactivelyReported: schema_js_1.s.optional(schema_js_1.s.boolean()),
|
||||
nonControllable: schema_js_1.s.optional(schema_js_1.s.boolean()),
|
||||
});
|
||||
/** One interface as an endpoint declares it: the descriptor, and what the declaration says about this endpoint. */
|
||||
class Capability {
|
||||
constructor(descriptor, declared) {
|
||||
this.descriptor = descriptor;
|
||||
/** The endpoint the capability is declared on; the device sets it. */
|
||||
this.endpointId = "";
|
||||
/** What the bridge logs about the declaration, once, when it answers a discovery. */
|
||||
this.notes = [];
|
||||
this.instance = declared.instance ?? "";
|
||||
this.friendlyNames = declared.friendlyNames ?? [];
|
||||
this.retrievable = declared.retrievable ?? true;
|
||||
this.proactivelyReported = declared.proactivelyReported ?? false;
|
||||
this.nonControllable = declared.nonControllable;
|
||||
this.options = declared.options;
|
||||
}
|
||||
get namespace() {
|
||||
return this.descriptor.namespace;
|
||||
}
|
||||
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
|
||||
get semantics() {
|
||||
const { semantics } = this.options;
|
||||
const mapped = (semantics?.actionMappings?.length ?? 0) + (semantics?.stateMappings?.length ?? 0);
|
||||
return mapped > 0 ? semantics : undefined;
|
||||
}
|
||||
/** The capability object for discovery, its fields in the order of the example on alexa-discovery-objects.html. */
|
||||
toJSON() {
|
||||
const { descriptor, semantics } = this;
|
||||
const extras = descriptor.discovery ? descriptor.discovery(this) : {};
|
||||
const json = {
|
||||
type: "AlexaInterface",
|
||||
interface: descriptor.namespace,
|
||||
...(this.instance ? { instance: this.instance } : {}),
|
||||
version: descriptor.version,
|
||||
};
|
||||
if (extras.properties !== false) {
|
||||
json.properties = {
|
||||
supported: Object.keys(descriptor.properties).map((name) => ({ name })),
|
||||
proactivelyReported: this.proactivelyReported,
|
||||
retrievable: this.retrievable,
|
||||
};
|
||||
if (this.nonControllable !== undefined)
|
||||
json.properties.nonControllable = this.nonControllable;
|
||||
}
|
||||
if (this.friendlyNames.length > 0)
|
||||
json.capabilityResources = { friendlyNames: this.friendlyNames };
|
||||
if (extras.configuration)
|
||||
json.configuration = extras.configuration;
|
||||
if (extras.configurations)
|
||||
json.configurations = extras.configurations;
|
||||
if (semantics)
|
||||
json.semantics = semantics;
|
||||
return { ...json, ...extras.topLevel };
|
||||
}
|
||||
}
|
||||
exports.Capability = Capability;
|
||||
270
dist/cjs/device/Device.js
vendored
Normal file
270
dist/cjs/device/Device.js
vendored
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const events_1 = require("events");
|
||||
const crypto_1 = require("crypto");
|
||||
const AlexaErrorResponse_js_1 = require("../AlexaErrorResponse.js");
|
||||
const AlexaStatusMessage_js_1 = require("../AlexaStatusMessage.js");
|
||||
const AlexaInterface_js_1 = require("../compat/AlexaInterface.js");
|
||||
const enums_js_1 = require("../compat/enums.js");
|
||||
const Alexa_js_1 = require("../registry/interfaces/Alexa.js");
|
||||
const EndpointHealth_js_1 = require("../registry/interfaces/EndpointHealth.js");
|
||||
const schema_js_1 = require("../registry/schema.js");
|
||||
const types_js_1 = require("../registry/types.js");
|
||||
const Capability_js_1 = require("./Capability.js");
|
||||
const validate_js_1 = require("./validate.js");
|
||||
class Device extends events_1.EventEmitter {
|
||||
constructor(mqttClient, rootTopic, name, endpointId, displayCategory, description = "Alexa to Node.js bridge", manufacturerName = "Alex2Node", manufacturer = "Alex2Node", model = "Alex2Node_v1.0.0") {
|
||||
super();
|
||||
this.mqttClient = mqttClient;
|
||||
this.rootTopic = rootTopic;
|
||||
this.name = name;
|
||||
this.endpointId = endpointId;
|
||||
this.displayCategory = displayCategory;
|
||||
this.description = description;
|
||||
this.manufacturerName = manufacturerName;
|
||||
this.manufacturer = manufacturer;
|
||||
this.model = model;
|
||||
this.softwareVersion = "1.0.0";
|
||||
this.serialNumber = "Alex2Node";
|
||||
this.firmwareVersion = "1.0.0";
|
||||
this.customIdentifier = "Alex2Node";
|
||||
/**
|
||||
* Discovery lists the Alexa interface on the endpoint (alexa-interface.html: "You must explicitly identify your
|
||||
* support for the Alexa interface"). The bridge sets it from its alexaInterface option.
|
||||
*/
|
||||
this.alexaInterface = true;
|
||||
/**
|
||||
* Discovery lists Alexa.EndpointHealth when the device did not declare it and is not a scene. On for a device of
|
||||
* bridge.addDevice(), off for one of registerDevice(), which is announced as 1.x announced it.
|
||||
*/
|
||||
this.endpointHealth = false;
|
||||
this.capabilities = [];
|
||||
}
|
||||
/** Internal (1.5.2): Alex2MQTT.connect() re-binds every registered device to its new broker client after a disconnect(). */
|
||||
setMqttClient(client) {
|
||||
this.mqttClient = client;
|
||||
}
|
||||
getName() {
|
||||
return this.name;
|
||||
}
|
||||
setName(name) {
|
||||
this.name = name;
|
||||
}
|
||||
getEndpointId() {
|
||||
return this.endpointId;
|
||||
}
|
||||
setDisplayCategory(category) {
|
||||
this.displayCategory = Array.isArray(category) ? category : [category];
|
||||
}
|
||||
getDisplayCategory() {
|
||||
return this.displayCategory || [enums_js_1.DisplayCategory.LIGHT];
|
||||
}
|
||||
setDescription(description) {
|
||||
this.description = description;
|
||||
}
|
||||
getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
getErrorMessage(correlationToken) {
|
||||
const msg = new AlexaErrorResponse_js_1.AlexaErrorResponse(correlationToken, this.rootTopic, this.endpointId, this.mqttClient);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
getStatusMessage(correlationToken, isResponse = false, isDeferred = false) {
|
||||
const msg = new AlexaStatusMessage_js_1.AlexaStatusMessage(correlationToken, this.rootTopic, this.endpointId, this.mqttClient, isResponse, isDeferred);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
/**
|
||||
* A proactive Alexa.ChangeReport (1.5.1): add the changed properties (the default target), optionally
|
||||
* .unchanged() then the others, and .send() - it goes to <root>/changeReport, which Alex2MQTT forwards to the Alexa
|
||||
* event gateway with the user's token. Alexa only accepts it for capabilities registered with proactivelyReported.
|
||||
*/
|
||||
getChangeReport(cause = "PHYSICAL_INTERACTION") {
|
||||
const msg = new AlexaStatusMessage_js_1.AlexaStatusMessage("", this.rootTopic, this.endpointId, this.mqttClient, false, false, cause);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
/**
|
||||
* Alexa.SceneController: answer an Activate / Deactivate directive with ActivationStarted / DeactivationStarted
|
||||
* (1.5.1). Resolves with the topic published to, or "" when the publish failed (never rejects, 1.5.2).
|
||||
*/
|
||||
sendSceneResponse(correlationToken, activated, cause = "VOICE_INTERACTION", sendAsync = false) {
|
||||
const payload = {
|
||||
context: {},
|
||||
event: {
|
||||
header: { namespace: "Alexa.SceneController", name: activated ? "ActivationStarted" : "DeactivationStarted", messageId: (0, crypto_1.randomUUID)(), correlationToken, payloadVersion: "3" },
|
||||
endpoint: { endpointId: this.endpointId },
|
||||
payload: { cause: { type: cause }, timestamp: new Date().toISOString() },
|
||||
},
|
||||
};
|
||||
const topic = `${this.rootTopic}/${this.endpointId}/${sendAsync ? "deferredResponse" : "alexaResponce"}`;
|
||||
return new Promise((resolve) => {
|
||||
this.mqttClient.publish(topic, JSON.stringify(payload), (err) => {
|
||||
if (!err)
|
||||
return resolve(topic);
|
||||
if (this.onPublishError)
|
||||
this.onPublishError(err); // -> the bridge's "error" event (when somebody listens)
|
||||
resolve(""); // 1.5.1 rejected here, and an un-caught send() then killed the host on any broker hiccup
|
||||
});
|
||||
});
|
||||
}
|
||||
/** The capabilities the device declared, in the order it declared them. */
|
||||
getCapabilities() {
|
||||
return this.capabilities.slice();
|
||||
}
|
||||
setManufacturerName(name) {
|
||||
this.manufacturerName = name;
|
||||
}
|
||||
getManufacturerName() {
|
||||
return this.manufacturerName;
|
||||
}
|
||||
setManufacturer(manufacturer) {
|
||||
this.manufacturer = manufacturer;
|
||||
}
|
||||
getManufacturer() {
|
||||
return this.manufacturer;
|
||||
}
|
||||
setModel(model) {
|
||||
this.model = model;
|
||||
}
|
||||
getModel() {
|
||||
return this.model;
|
||||
}
|
||||
getSoftwareVersion() {
|
||||
return this.softwareVersion;
|
||||
}
|
||||
/**
|
||||
* Declare an interface of the device:
|
||||
*
|
||||
* lamp.add(PowerController, { proactivelyReported: true });
|
||||
* blinds.add(RangeController, { instance: "Blind.Lift", friendlyNames: [asset("Alexa.Setting.Opening")],
|
||||
* range: { min: 0, max: 100, precision: 1 } });
|
||||
*
|
||||
* Throws a DeclarationError that names the endpoint, the interface and the instance when Alexa would reject the
|
||||
* capability; the device is then as it was before the call.
|
||||
*/
|
||||
add(descriptor, ...[options]) {
|
||||
const where = { endpointId: this.endpointId, namespace: descriptor.namespace, instance: "" };
|
||||
if (options !== undefined && (typeof options !== "object" || options === null)) {
|
||||
throw new types_js_1.DeclarationError(where, "the options of a declaration are an object");
|
||||
}
|
||||
try {
|
||||
const { instance, friendlyNames, retrievable, proactivelyReported, nonControllable, ...given } = Capability_js_1.commonOptions.parse(options ?? {});
|
||||
where.instance = instance ?? "";
|
||||
const common = { instance, friendlyNames: friendlyNames, retrievable, proactivelyReported, nonControllable };
|
||||
const capability = new Capability_js_1.Capability(descriptor, { ...common, options: interfaceOptions(descriptor, given) });
|
||||
capability.endpointId = this.endpointId;
|
||||
(0, validate_js_1.checkCapability)(capability, descriptor, this.view(this.capabilities));
|
||||
(0, validate_js_1.checkCapabilityCount)(this.endpointId, this.announced([...this.capabilities, capability]).length);
|
||||
this.capabilities.push(capability);
|
||||
return capability;
|
||||
}
|
||||
catch (err) {
|
||||
throw err instanceof schema_js_1.SchemaError ? new types_js_1.DeclarationError(where, err.message) : err;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Declare an interface the 1.x way, by its name: options.retrievable / proactivelyReported / instance, then the
|
||||
* add and set methods of the capability that is returned. Throws for a name that is not an interface. Anything
|
||||
* else Alexa would reject is not refused here: check() lists it.
|
||||
*/
|
||||
addCapability(type, options = {}) {
|
||||
let capability;
|
||||
try {
|
||||
capability = new AlexaInterface_js_1.AlexaInterface(type, options.retrievable ?? true, options.proactivelyReported ?? false, options.instance ?? "");
|
||||
}
|
||||
catch (err) {
|
||||
throw err instanceof types_js_1.DeclarationError ? new types_js_1.DeclarationError({ endpointId: this.endpointId }, err.problem) : err;
|
||||
}
|
||||
capability.endpointId = this.endpointId;
|
||||
this.capabilities.push(capability);
|
||||
return capability;
|
||||
}
|
||||
/**
|
||||
* What Alexa would reject in the device as it is declared now, one line for each: a name with punctuation, an
|
||||
* interface declared twice. Also what a capability noted about its declaration. Empty when there is nothing.
|
||||
* The bridge logs the lines when it answers a discovery.
|
||||
*/
|
||||
check() {
|
||||
const lines = [];
|
||||
const attempt = (rule) => {
|
||||
try {
|
||||
rule();
|
||||
}
|
||||
catch (err) {
|
||||
if (!(err instanceof types_js_1.DeclarationError))
|
||||
throw err;
|
||||
lines.push(err.message);
|
||||
}
|
||||
};
|
||||
attempt(() => (0, validate_js_1.checkEndpoint)(this.fields()));
|
||||
this.capabilities.forEach((capability, i) => {
|
||||
capability.endpointId = this.endpointId;
|
||||
attempt(() => (0, validate_js_1.checkCapability)(capability, capability.descriptor, this.view(this.capabilities.slice(0, i))));
|
||||
const notes = [...capability.notes];
|
||||
const { tier, properties } = capability.descriptor;
|
||||
if (tier === 3 && Object.keys(properties).length === 0 && capability.toJSON().properties) {
|
||||
notes.push("no property list known, discovery lists it with no supported properties");
|
||||
}
|
||||
for (const note of notes)
|
||||
lines.push(new types_js_1.DeclarationError(capability, note).message);
|
||||
});
|
||||
attempt(() => (0, validate_js_1.checkCapabilityCount)(this.endpointId, this.announced(this.capabilities).length));
|
||||
return lines;
|
||||
}
|
||||
/** The endpoint object for discovery. */
|
||||
getJSON() {
|
||||
return { ...this.fields(), capabilities: this.announced(this.capabilities).map((capability) => capability.toJSON()) };
|
||||
}
|
||||
fields() {
|
||||
return {
|
||||
endpointId: this.endpointId,
|
||||
friendlyName: this.name,
|
||||
description: this.description,
|
||||
manufacturerName: this.manufacturerName,
|
||||
displayCategories: this.getDisplayCategory(),
|
||||
additionalAttributes: {
|
||||
manufacturer: this.manufacturer,
|
||||
model: this.model,
|
||||
serialNumber: this.serialNumber,
|
||||
firmwareVersion: this.firmwareVersion,
|
||||
softwareVersion: this.softwareVersion,
|
||||
customIdentifier: this.customIdentifier,
|
||||
},
|
||||
...(this.cookie ? { cookie: this.cookie } : {}),
|
||||
};
|
||||
}
|
||||
// The endpoint as the rules of a capability see it
|
||||
view(declaredBefore) {
|
||||
return {
|
||||
endpointId: this.endpointId,
|
||||
friendlyName: this.name,
|
||||
description: this.description,
|
||||
displayCategories: this.getDisplayCategory(),
|
||||
capabilities: declaredBefore,
|
||||
};
|
||||
}
|
||||
// What discovery lists: the declared capabilities, then the ones the library adds
|
||||
announced(declared) {
|
||||
const has = (namespace) => declared.some((capability) => capability.namespace === namespace);
|
||||
const added = [];
|
||||
// alexa-scenecontroller.html, "Discovery": a scene is not a physical device and has no Alexa.EndpointHealth
|
||||
if (this.endpointHealth && !has(EndpointHealth_js_1.EndpointHealth.namespace) && !has("Alexa.SceneController")) {
|
||||
added.push(new Capability_js_1.Capability(EndpointHealth_js_1.EndpointHealth, { options: {} }));
|
||||
}
|
||||
if (this.alexaInterface && !has(Alexa_js_1.Alexa.namespace))
|
||||
added.push(new Capability_js_1.Capability(Alexa_js_1.Alexa, { options: {} }));
|
||||
return [...declared, ...added];
|
||||
}
|
||||
}
|
||||
// The options of the interface itself, checked by the schema of its descriptor
|
||||
function interfaceOptions(descriptor, given) {
|
||||
if (descriptor.options)
|
||||
return descriptor.options.parse(given);
|
||||
const [unknown] = Object.keys(given);
|
||||
if (unknown !== undefined)
|
||||
throw new schema_js_1.SchemaError(unknown, "not an option of the interface");
|
||||
return {};
|
||||
}
|
||||
exports.default = Device;
|
||||
128
dist/cjs/device/validate.js
vendored
Normal file
128
dist/cjs/device/validate.js
vendored
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.checkEndpoint = checkEndpoint;
|
||||
exports.checkCapabilityCount = checkCapabilityCount;
|
||||
exports.checkCapability = checkCapability;
|
||||
// What Alexa rejects at discovery, checked where a device is declared. Alexa gives no reason when it drops an
|
||||
// endpoint: the user hears "no new devices found". Each rule names the page it is from.
|
||||
const catalog_js_1 = require("../registry/catalog.js");
|
||||
const resources_js_1 = require("../registry/resources.js");
|
||||
const schema_js_1 = require("../registry/schema.js");
|
||||
const types_js_1 = require("../registry/types.js");
|
||||
// alexa-discovery-objects.html, "Endpoint object details": "letters, numbers, spaces, and the following special
|
||||
// characters: _ - = # ; : ? @ &"
|
||||
const ENDPOINT_ID = /^[A-Za-z0-9 _\-=#;:?@&]+$/;
|
||||
// Same table: "alphanumeric characters and spaces". Letters of any script: Alexa speaks Hindi and Japanese too.
|
||||
const FRIENDLY_NAME = /^[\p{L}\p{M}\p{N} ]+$/u;
|
||||
const isText = (value) => typeof value === "string" && value.length > 0;
|
||||
/** Throws the first rule of the Endpoint object that the fields break. */
|
||||
function checkEndpoint(endpoint) {
|
||||
const where = { endpointId: isText(endpoint.endpointId) ? endpoint.endpointId : undefined };
|
||||
function refuse(problem) {
|
||||
throw new types_js_1.DeclarationError(where, problem);
|
||||
}
|
||||
const { endpointId, friendlyName, description, manufacturerName, displayCategories, additionalAttributes, cookie } = endpoint;
|
||||
if (!isText(endpointId))
|
||||
refuse("an endpoint needs an endpointId");
|
||||
if (endpointId.length > catalog_js_1.LIMITS.endpointIdLength || !ENDPOINT_ID.test(endpointId)) {
|
||||
refuse(`the endpointId takes up to ${catalog_js_1.LIMITS.endpointIdLength} letters, digits, spaces and _ - = # ; : ? @ &`);
|
||||
}
|
||||
if (!isText(friendlyName))
|
||||
refuse("an endpoint needs a name");
|
||||
if (friendlyName.length > catalog_js_1.LIMITS.friendlyNameLength || !FRIENDLY_NAME.test(friendlyName)) {
|
||||
refuse(`the name ${JSON.stringify(friendlyName)} takes up to ${catalog_js_1.LIMITS.friendlyNameLength} letters, digits and spaces, no punctuation`);
|
||||
}
|
||||
if (!isText(manufacturerName) || manufacturerName.length > catalog_js_1.LIMITS.manufacturerNameLength) {
|
||||
refuse(`the manufacturerName takes 1 to ${catalog_js_1.LIMITS.manufacturerNameLength} characters`);
|
||||
}
|
||||
if (!isText(description) || description.length > catalog_js_1.LIMITS.descriptionLength) {
|
||||
refuse(`the description takes 1 to ${catalog_js_1.LIMITS.descriptionLength} characters`);
|
||||
}
|
||||
if (!Array.isArray(displayCategories) || displayCategories.length === 0)
|
||||
refuse("an endpoint needs a display category");
|
||||
const known = catalog_js_1.DISPLAY_CATEGORIES;
|
||||
for (const category of displayCategories) {
|
||||
if (!known.includes(category))
|
||||
refuse(`${JSON.stringify(category)} is not a display category`);
|
||||
}
|
||||
for (const [name, value] of Object.entries(additionalAttributes)) {
|
||||
if (typeof value !== "string" || value.length > catalog_js_1.LIMITS.additionalAttributeLength) {
|
||||
refuse(`${name} takes up to ${catalog_js_1.LIMITS.additionalAttributeLength} characters`);
|
||||
}
|
||||
}
|
||||
if (cookie !== undefined) {
|
||||
const bytes = Buffer.byteLength(JSON.stringify(cookie) ?? "");
|
||||
if (bytes > catalog_js_1.LIMITS.cookieBytes)
|
||||
refuse(`the cookie is ${bytes} bytes, ${catalog_js_1.LIMITS.cookieBytes} is the most`);
|
||||
}
|
||||
}
|
||||
/** alexa-discovery.html, "Interface limits". count includes the capabilities the library adds. */
|
||||
function checkCapabilityCount(endpointId, count) {
|
||||
if (count > catalog_js_1.LIMITS.capabilitiesPerEndpoint) {
|
||||
throw new types_js_1.DeclarationError({ endpointId }, `${count} capabilities, an endpoint takes ${catalog_js_1.LIMITS.capabilitiesPerEndpoint}`);
|
||||
}
|
||||
}
|
||||
// Two names are the same name when the app would show the same: the asset, or the text in one locale.
|
||||
function nameKey(name) {
|
||||
return name["@type"] === "asset" ? `asset ${name.value.assetId}` : `text ${name.value.locale} ${name.value.text.toLowerCase()}`;
|
||||
}
|
||||
function phrases(capability) {
|
||||
const { semantics } = capability.options;
|
||||
return (semantics?.actionMappings ?? []).flatMap((mapping) => mapping.actions);
|
||||
}
|
||||
/**
|
||||
* Throws the first rule that a capability breaks on its endpoint. endpoint.capabilities are the ones declared
|
||||
* before it. A stub is checked for being declared twice and for nothing else: the library does not know its rules.
|
||||
*/
|
||||
function checkCapability(capability, descriptor, endpoint) {
|
||||
function refuse(problem) {
|
||||
throw new types_js_1.DeclarationError(capability, problem);
|
||||
}
|
||||
const { namespace, instance, friendlyNames } = capability;
|
||||
// generic-controllers.html, "Multiple instances": one capability of an interface, or one per instance name
|
||||
if (endpoint.capabilities.some((other) => other.namespace === namespace && other.instance === instance)) {
|
||||
refuse(instance ? "the instance is declared twice" : "the interface is declared twice");
|
||||
}
|
||||
if (descriptor.tier === 3)
|
||||
return;
|
||||
if (descriptor.instanced) {
|
||||
// alexa-rangecontroller.html, "Capabilities array": instance and capabilityResources are required
|
||||
if (!isText(instance))
|
||||
refuse("needs an instance name, like Blind.Lift");
|
||||
try {
|
||||
resources_js_1.labels.parse(friendlyNames, "friendlyNames");
|
||||
}
|
||||
catch (err) {
|
||||
refuse(err instanceof schema_js_1.SchemaError && err.path === "friendlyNames" ? "needs a friendly name, from text() or asset()" : err.message);
|
||||
}
|
||||
// resources-and-assets.html, "CapabilityResources": "The first friendly name in the array must be unique for
|
||||
// the endpoint."
|
||||
const first = nameKey(friendlyNames[0]);
|
||||
const taken = endpoint.capabilities.find((other) => other.friendlyNames.length > 0 && nameKey(other.friendlyNames[0]) === first);
|
||||
if (taken) {
|
||||
refuse(`the first friendly name, ${(0, resources_js_1.shownAs)(friendlyNames[0])}, is the first of ${taken.namespace} ${JSON.stringify(taken.instance)} too`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (instance)
|
||||
refuse("takes no instance name: an endpoint has the interface once");
|
||||
if (friendlyNames.length > 0)
|
||||
refuse("takes no friendly names");
|
||||
}
|
||||
// generic-controllers.html, "Semantics for user utterances": "Each semantic phrase must be unique across all
|
||||
// controller instances for each endpoint"
|
||||
const used = new Map();
|
||||
for (const other of endpoint.capabilities)
|
||||
for (const phrase of phrases(other))
|
||||
used.set(phrase, other);
|
||||
for (const phrase of phrases(capability)) {
|
||||
const owner = used.get(phrase);
|
||||
if (owner) {
|
||||
const place = owner === capability ? "twice" : `here and on ${owner.namespace} ${JSON.stringify(owner.instance)}`;
|
||||
refuse(`${phrase} is mapped ${place}, an endpoint maps a phrase once`);
|
||||
}
|
||||
used.set(phrase, capability);
|
||||
}
|
||||
if (descriptor.validate)
|
||||
descriptor.validate(capability, endpoint);
|
||||
}
|
||||
63
dist/cjs/index.js
vendored
63
dist/cjs/index.js
vendored
|
|
@ -3,38 +3,51 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.DisplayCategories = exports.States = exports.Actions = exports.Units = exports.Assets = exports.SchemaError = exports.DeclarationError = exports.registry = exports.AlexaErrorResponse = exports.AlexaErrorType = exports.ThermostatMode = exports.TemperatureSensorScale = exports.EndpointHealth = exports.PowerController = exports.AlexaStatusMessage = exports.DisplayCategory = exports.AlexaActions = exports.ActionMapping = exports.AlexaInterfaceType = exports.AlexaInterface = 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.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;
|
||||
// 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");
|
||||
Object.defineProperty(exports, "Alex2MQTT", { enumerable: true, get: function () { return __importDefault(Alex2Node_js_1).default; } });
|
||||
Object.defineProperty(exports, "DEFAULT_HOST", { enumerable: true, get: function () { return Alex2Node_js_1.DEFAULT_HOST; } });
|
||||
var Device_js_1 = require("./Device.js");
|
||||
var Device_js_1 = require("./device/Device.js");
|
||||
Object.defineProperty(exports, "Device", { enumerable: true, get: function () { return __importDefault(Device_js_1).default; } });
|
||||
var AlexaInterface_js_1 = require("./AlexaInterface.js");
|
||||
Object.defineProperty(exports, "AlexaInterface", { enumerable: true, get: function () { return AlexaInterface_js_1.AlexaInterface; } });
|
||||
Object.defineProperty(exports, "AlexaInterfaceType", { enumerable: true, get: function () { return AlexaInterface_js_1.AlexaInterfaceType; } });
|
||||
var ActionMapping_js_1 = require("./ActionMapping.js");
|
||||
Object.defineProperty(exports, "ActionMapping", { enumerable: true, get: function () { return ActionMapping_js_1.ActionMapping; } });
|
||||
Object.defineProperty(exports, "AlexaActions", { enumerable: true, get: function () { return ActionMapping_js_1.AlexaActions; } });
|
||||
var DisplayCategory_js_1 = require("./DisplayCategory.js");
|
||||
Object.defineProperty(exports, "DisplayCategory", { enumerable: true, get: function () { return DisplayCategory_js_1.DisplayCategory; } });
|
||||
var AlexaStatusMessage_js_1 = require("./AlexaStatusMessage.js");
|
||||
Object.defineProperty(exports, "AlexaStatusMessage", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.AlexaStatusMessage; } });
|
||||
Object.defineProperty(exports, "PowerController", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.PowerController; } });
|
||||
Object.defineProperty(exports, "EndpointHealth", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.EndpointHealth; } });
|
||||
Object.defineProperty(exports, "TemperatureSensorScale", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.TemperatureSensorScale; } });
|
||||
Object.defineProperty(exports, "ThermostatMode", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.ThermostatMode; } });
|
||||
var AlexaErrorResponse_js_1 = require("./AlexaErrorResponse.js");
|
||||
Object.defineProperty(exports, "AlexaErrorType", { enumerable: true, get: function () { return AlexaErrorResponse_js_1.AlexaErrorType; } });
|
||||
Object.defineProperty(exports, "AlexaErrorResponse", { enumerable: true, get: function () { return AlexaErrorResponse_js_1.AlexaErrorResponse; } });
|
||||
// The interface registry and the vocabularies of the Smart Home API
|
||||
var Capability_js_1 = require("./device/Capability.js");
|
||||
Object.defineProperty(exports, "Capability", { enumerable: true, get: function () { return Capability_js_1.Capability; } });
|
||||
// The interfaces, for device.add(), and the registry that holds them by name
|
||||
var index_js_1 = require("./registry/index.js");
|
||||
Object.defineProperty(exports, "registry", { enumerable: true, get: function () { return index_js_1.registry; } });
|
||||
Object.defineProperty(exports, "DeclarationError", { enumerable: true, get: function () { return index_js_1.DeclarationError; } });
|
||||
Object.defineProperty(exports, "SchemaError", { enumerable: true, get: function () { return index_js_1.SchemaError; } });
|
||||
var index_js_2 = require("./registry/index.js");
|
||||
Object.defineProperty(exports, "Assets", { enumerable: true, get: function () { return index_js_2.ASSETS; } });
|
||||
Object.defineProperty(exports, "Units", { enumerable: true, get: function () { return index_js_2.UNITS_OF_MEASURE; } });
|
||||
Object.defineProperty(exports, "Actions", { enumerable: true, get: function () { return index_js_2.ACTIONS; } });
|
||||
Object.defineProperty(exports, "States", { enumerable: true, get: function () { return index_js_2.STATES; } });
|
||||
Object.defineProperty(exports, "DisplayCategories", { enumerable: true, get: function () { return index_js_2.DISPLAY_CATEGORIES; } });
|
||||
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, "TemperatureSensor", { enumerable: true, get: function () { return index_js_2.TemperatureSensor; } });
|
||||
var enums_js_1 = require("./compat/enums.js");
|
||||
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; } });
|
||||
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");
|
||||
Object.defineProperty(exports, "Assets", { enumerable: true, get: function () { return index_js_3.ASSETS; } });
|
||||
Object.defineProperty(exports, "Units", { enumerable: true, get: function () { return index_js_3.UNITS_OF_MEASURE; } });
|
||||
Object.defineProperty(exports, "Actions", { enumerable: true, get: function () { return index_js_3.ACTIONS; } });
|
||||
Object.defineProperty(exports, "States", { enumerable: true, get: function () { return index_js_3.STATES; } });
|
||||
Object.defineProperty(exports, "DisplayCategories", { enumerable: true, get: function () { return index_js_3.DISPLAY_CATEGORIES; } });
|
||||
// 1.x
|
||||
var AlexaInterface_js_1 = require("./compat/AlexaInterface.js");
|
||||
Object.defineProperty(exports, "AlexaInterface", { enumerable: true, get: function () { return AlexaInterface_js_1.AlexaInterface; } });
|
||||
var ActionMapping_js_1 = require("./compat/ActionMapping.js");
|
||||
Object.defineProperty(exports, "ActionMapping", { enumerable: true, get: function () { return ActionMapping_js_1.ActionMapping; } });
|
||||
var enums_js_2 = require("./compat/enums.js");
|
||||
Object.defineProperty(exports, "AlexaActions", { enumerable: true, get: function () { return enums_js_2.AlexaActions; } });
|
||||
Object.defineProperty(exports, "AlexaInterfaceType", { enumerable: true, get: function () { return enums_js_2.AlexaInterfaceType; } });
|
||||
Object.defineProperty(exports, "DisplayCategory", { enumerable: true, get: function () { return enums_js_2.DisplayCategory; } });
|
||||
Object.defineProperty(exports, "PowerState", { enumerable: true, get: function () { return enums_js_2.PowerState; } });
|
||||
var AlexaStatusMessage_js_1 = require("./AlexaStatusMessage.js");
|
||||
Object.defineProperty(exports, "AlexaStatusMessage", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.AlexaStatusMessage; } });
|
||||
Object.defineProperty(exports, "TemperatureSensorScale", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.TemperatureSensorScale; } });
|
||||
Object.defineProperty(exports, "ThermostatMode", { enumerable: true, get: function () { return AlexaStatusMessage_js_1.ThermostatMode; } });
|
||||
var AlexaErrorResponse_js_1 = require("./AlexaErrorResponse.js");
|
||||
Object.defineProperty(exports, "AlexaErrorType", { enumerable: true, get: function () { return AlexaErrorResponse_js_1.AlexaErrorType; } });
|
||||
Object.defineProperty(exports, "AlexaErrorResponse", { enumerable: true, get: function () { return AlexaErrorResponse_js_1.AlexaErrorResponse; } });
|
||||
|
|
|
|||
15
dist/cjs/registry/interfaces/stubs.js
vendored
15
dist/cjs/registry/interfaces/stubs.js
vendored
|
|
@ -80,6 +80,20 @@ const TABLE = [
|
|||
["Alexa.VideoRecorder", "1", [], "alexa-videorecorder.html"],
|
||||
["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"],
|
||||
];
|
||||
// What 1.5.2 added to the capability object of three of them
|
||||
const EXTRAS = {
|
||||
// No properties object; supportsDeactivation and proactivelyReported on the capability itself
|
||||
"Alexa.SceneController": ({ proactivelyReported }) => ({
|
||||
properties: false,
|
||||
topLevel: { supportsDeactivation: true, proactivelyReported },
|
||||
}),
|
||||
"Alexa.ThermostatController": () => ({
|
||||
configuration: { supportedModes: ["HEAT", "COOL", "AUTO", "OFF"], supportsScheduling: false },
|
||||
}),
|
||||
"Alexa.ModeController": ({ options }) => (options.supportedModes?.length > 0
|
||||
? { configuration: { ordered: true, supportedModes: options.supportedModes } }
|
||||
: {}),
|
||||
};
|
||||
function kindOf(namespace) {
|
||||
if (namespace.endsWith("Sensor"))
|
||||
return "sensor";
|
||||
|
|
@ -97,6 +111,7 @@ function stub([namespace, version, properties, page]) {
|
|||
instanced: false,
|
||||
properties: Object.fromEntries(properties.map((name) => [name, { name, value: schema_js_1.s.unknown() }])),
|
||||
directives: {},
|
||||
discovery: EXTRAS[namespace],
|
||||
};
|
||||
}
|
||||
exports.STUBS = TABLE.map(stub);
|
||||
|
|
|
|||
45
dist/cjs/registry/resources.js
vendored
Normal file
45
dist/cjs/registry/resources.js
vendored
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.labels = exports.label = void 0;
|
||||
exports.text = text;
|
||||
exports.asset = asset;
|
||||
exports.shownAs = shownAs;
|
||||
// Friendly names: what the user calls an instance, a mode or a preset (resources-and-assets.html).
|
||||
const catalog_js_1 = require("./catalog.js");
|
||||
const schema_js_1 = require("./schema.js");
|
||||
/** A friendly name as text, in one locale. */
|
||||
function text(name, locale = "en-US") {
|
||||
return { "@type": "text", value: { text: name, locale } };
|
||||
}
|
||||
/** A friendly name from the global Alexa catalog: one id, several names, every language Alexa speaks. */
|
||||
function asset(assetId) {
|
||||
return { "@type": "asset", value: { assetId } };
|
||||
}
|
||||
const LOCALE = /^[a-z]{2}-[A-Z]{2}$/;
|
||||
const textValue = schema_js_1.s.object({
|
||||
text: schema_js_1.s.string({ min: 1 }),
|
||||
locale: schema_js_1.s.string({ pattern: LOCALE, expects: "a locale like en-US" }),
|
||||
});
|
||||
const assetValue = schema_js_1.s.object({ assetId: schema_js_1.s.oneOf(catalog_js_1.ASSETS, "an id of the global Alexa catalog, like Alexa.Setting.Opening") });
|
||||
const typed = schema_js_1.s.object({ "@type": schema_js_1.s.enum("text", "asset"), value: schema_js_1.s.unknown() });
|
||||
const reserved = catalog_js_1.RESERVED_WORDS;
|
||||
/** One friendly name. An asset has to be in the catalog, a text must not be a word Alexa keeps for itself. */
|
||||
exports.label = {
|
||||
expects: "a friendly name, from text() or asset()",
|
||||
parse(input, path = "") {
|
||||
const { "@type": type, value } = typed.parse(input, path);
|
||||
if (type === "asset")
|
||||
return { "@type": type, value: assetValue.parse(value, (0, schema_js_1.at)(path, "value")) };
|
||||
const named = textValue.parse(value, (0, schema_js_1.at)(path, "value"));
|
||||
if (reserved.includes(named.text.trim().toLowerCase())) {
|
||||
throw new schema_js_1.SchemaError((0, schema_js_1.at)(path, "value.text"), `${JSON.stringify(named.text)} is a reserved word, not to be used as a friendly name`);
|
||||
}
|
||||
return { "@type": type, value: named };
|
||||
},
|
||||
};
|
||||
/** The friendly names of an instance, a mode or a preset: at least one. */
|
||||
exports.labels = schema_js_1.s.array(exports.label, { min: 1 });
|
||||
/** What the user is shown for a friendly name: the text, or the id of the asset. */
|
||||
function shownAs(name) {
|
||||
return name["@type"] === "text" ? name.value.text : name.value.assetId;
|
||||
}
|
||||
17
dist/cjs/registry/schema.js
vendored
17
dist/cjs/registry/schema.js
vendored
|
|
@ -3,7 +3,8 @@
|
|||
// and declaration options with these; parse() returns the value or throws a SchemaError that names where it went
|
||||
// wrong. Written here rather than taken from a package: mqtt stays the only runtime dependency.
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.s = exports.SchemaError = void 0;
|
||||
exports.s = exports.at = exports.SchemaError = void 0;
|
||||
exports.mismatch = mismatch;
|
||||
/** A value that does not fit its schema: path is where ("payload.targetSetpoint.scale"), problem is what. */
|
||||
class SchemaError extends Error {
|
||||
constructor(path, problem) {
|
||||
|
|
@ -23,10 +24,13 @@ function shown(input) {
|
|||
const text = JSON.stringify(input) ?? String(input);
|
||||
return text.length > 60 ? `${text.slice(0, 57)}...` : text;
|
||||
}
|
||||
/** The error of a value that is not what a schema expects. */
|
||||
function mismatch(path, expects, input) {
|
||||
return new SchemaError(path, `expected ${expects}, got ${shown(input)}`);
|
||||
}
|
||||
/** The path of a key of the object at path. */
|
||||
const at = (path, key) => (path ? `${path}.${key}` : key);
|
||||
exports.at = at;
|
||||
function isRecord(input) {
|
||||
return typeof input === "object" && input !== null && !Array.isArray(input);
|
||||
}
|
||||
|
|
@ -69,7 +73,11 @@ function literal(value) {
|
|||
return schema(JSON.stringify(value), (input) => input === value);
|
||||
}
|
||||
function enumeration(...values) {
|
||||
return { ...schema(values.join(" | "), (input) => values.includes(input)), values };
|
||||
return oneOf(values, values.join(" | "));
|
||||
}
|
||||
/** One of a list too long to print in an error message: expects says what the list is. */
|
||||
function oneOf(values, expects) {
|
||||
return { ...schema(expects, (input) => values.includes(input)), values };
|
||||
}
|
||||
function unknown() {
|
||||
return schema("any value", () => true);
|
||||
|
|
@ -127,11 +135,11 @@ function object(shape, rules = {}) {
|
|||
throw mismatch(path, expects, input);
|
||||
const others = Object.keys(input).filter((key) => !known.includes(key));
|
||||
if (others.length > 0 && rules.unknownKeys === "reject") {
|
||||
throw new SchemaError(at(path, others[0]), `unknown key, the known ones are ${known.join(", ") || "none"}`);
|
||||
throw new SchemaError((0, exports.at)(path, others[0]), `unknown key, the known ones are ${known.join(", ") || "none"}`);
|
||||
}
|
||||
const parsed = {};
|
||||
for (const key of known) {
|
||||
const value = shape[key].parse(input[key], at(path, key));
|
||||
const value = shape[key].parse(input[key], (0, exports.at)(path, key));
|
||||
if (value !== undefined)
|
||||
parsed[key] = value;
|
||||
}
|
||||
|
|
@ -178,6 +186,7 @@ exports.s = {
|
|||
boolean,
|
||||
literal,
|
||||
enum: enumeration,
|
||||
oneOf,
|
||||
unknown,
|
||||
optional,
|
||||
nullable,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue