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
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;
|
||||
Loading…
Add table
Add a link
Reference in a new issue