Alex2Node/src/device/Device.ts
David 2cbcde563e device: changeReport(cause, fill) sends a ChangeReport on the 2.0 API
The design has it (section 5) and 2.0 lacked it: a ChangeReport could only be
sent with getChangeReport() of 1.x, which has no helper for a contact or a
motion sensor. fill sets what changed, and after unchanged() what did not;
the rest of the context is the state of device.state(). The report goes to
<root>/changeReport. It throws MessageError without a changed property and
resolves with the failure when the device is on no bridge, as raise() does.
Four tests in test/device/raise.test.js.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 21:37:37 +00:00

505 lines
22 KiB
TypeScript

import { EventEmitter } from "events";
import { AlexaErrorResponse } from "../compat/AlexaErrorResponse.js";
import { AlexaInterface } from "../compat/AlexaInterface.js";
import { AlexaStatusMessage } from "../compat/AlexaStatusMessage.js";
import { DisplayCategory } from "../compat/enums.js";
import type { AlexaInterfaceType } from "../compat/enums.js";
import { changeReport, MessageError, proactiveEvent, sameProperty, sceneEvent } from "../messages/build.js";
import { StateBuilder } from "../messages/StateBuilder.js";
import type { ChangeCause } from "../messages/types.js";
import type { DirectiveHandler, Fill } from "../dispatcher.js";
import type { DisplayCategoryName } from "../registry/catalog.js";
import { Alexa } from "../registry/interfaces/Alexa.js";
import { EndpointHealth } from "../registry/interfaces/EndpointHealth.js";
import { SceneController } from "../registry/interfaces/SceneController.js";
import { SchemaError } from "../registry/schema.js";
import { DeclarationError } from "../registry/types.js";
import type { Directives, EndpointView, InterfaceDescriptor, Label, Properties } from "../registry/types.js";
import * as topics from "../topics.js";
import { send } from "../transport.js";
import type { Publisher, PublishResult } from "../transport.js";
import { Capability, commonOptions } from "./Capability.js";
import type { AnyCapability, CapabilityJson, Declaration } from "./Capability.js";
import { checkCapability, checkCapabilityCount, checkEndpoint } from "./validate.js";
import type { EndpointFields } from "./validate.js";
/** An endpoint as bridge.addDevice() takes it. */
export interface EndpointDefinition {
/** Up to 256 letters, digits, spaces and _ - = # ; : ? @ &. The same id at every discovery. */
endpointId: string;
/** What the user calls the device: letters, digits and spaces. */
name: string;
/** The first one is the category the Alexa app shows the device under. */
categories: Array<DisplayCategoryName | DisplayCategory>;
/** Shown in the Alexa app, up to 128 characters. Default: "Alexa to Node.js bridge". */
description?: string;
/** Up to 128 characters. Default: "Alex2Node". */
manufacturerName?: string;
// additionalAttributes: Alexa tells two devices apart by them when two add-ons report the same one
manufacturer?: string;
model?: string;
serialNumber?: string;
firmwareVersion?: string;
softwareVersion?: string;
customIdentifier?: string;
/** Returned with every directive to the endpoint. Up to 5000 bytes; not a place for state. */
cookie?: Record<string, string>;
/** false: the device gets no Alexa.EndpointHealth unless it declares one. */
endpointHealth?: boolean;
}
/** An endpoint object of a discovery answer (alexa-discovery-objects.html, "Endpoint object"). */
export interface EndpointJson extends EndpointFields {
capabilities: CapabilityJson[];
}
// device.add(PowerController) needs no options, device.add(RangeController) cannot do without
type DeclarationArguments<O, I extends boolean> = {} extends Declaration<O, I>
? [options?: Declaration<O, I>]
: [options: Declaration<O, I>];
// The 1.x calls that were reported as no longer doing anything: each is said once in a process
const reported = new Set<string>();
class Device extends EventEmitter {
public softwareVersion = "1.0.0";
public serialNumber = "Alex2Node";
public firmwareVersion = "1.0.0";
public customIdentifier = "Alex2Node";
public cookie?: Record<string, string>;
/**
* 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.
*/
public 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.
*/
public endpointHealth = false;
private capabilities: AnyCapability[] = [];
/** Where a failed publish from this device or a message it built is reported; Alex2MQTT sets it (1.5.2). */
public onPublishError?: (err: Error) => void;
/**
* What the device and the messages it builds publish through. The bridge sets it when the device is registered
* and clears it when the device is unregistered; a MemoryPublisher here tests a device without a broker. While it
* is null every send() resolves "" and reports why.
*/
public publisher: Publisher | null = null;
/** Where the device says that a call of 1.x no longer does anything. The bridge sets it to its log hook. */
public log?: (message: string) => void;
/** Set by state(). */
public stateProvider?: Fill;
/** Set by onReportState(). */
public reportStateHandler?: DirectiveHandler<Record<string, never>>;
/** Set by onDirective(). */
public directiveHandler?: DirectiveHandler;
/**
* client is ignored and null is what to pass: in 1.x it was the broker client, and a device could only be built
* after connect(). A device that is given one says once that it publishes through its bridge.
*
* @deprecated Removed in 3.0, with the device made by bridge.addDevice() or bridge.registerDevice().
*/
constructor(
client: unknown,
private rootTopic: string,
public name: string,
public endpointId: string,
public displayCategory: Array<DisplayCategory> | null,
public description: string = "Alexa to Node.js bridge",
public manufacturerName: string = "Alex2Node",
public manufacturer: string = "Alex2Node",
public model: string = "Alex2Node_v1.0.0"
) {
super();
if (client !== null && client !== undefined) {
this.deprecated(
"ALEX2NODE_DEVICE_CLIENT",
"new Device(client, ...) ignores the client since 2.0: nothing is published through it. "
+ "Make the device with addDevice() or registerDevice() of the bridge, or set device.publisher"
);
}
}
/**
* Does nothing. In 1.5.2 the bridge gave its devices the new broker client after disconnect() and connect();
* they now publish through the bridge and need no client.
*
* @deprecated Removed in 3.0. Remove the call, or set device.publisher to publish somewhere else.
*/
setMqttClient(_client: unknown): void {
this.deprecated(
"ALEX2NODE_SET_MQTT_CLIENT",
"device.setMqttClient() does nothing since 2.0: a device publishes through its bridge, over disconnect() and "
+ "connect() too. Remove the call, or set device.publisher to publish somewhere else"
);
}
// Through the log hook of the bridge. A device on no bridge has none and warns as Node does for a deprecation:
// once on stderr, to process.on("warning"), and not at all under --no-deprecation.
private deprecated(code: string, message: string): void {
if (reported.has(code)) return;
reported.add(code);
if (this.log) this.log(`warning: ${message}`);
else process.emitWarning(message, { type: "DeprecationWarning", code });
}
getName(): string {
return this.name;
}
setName(name: string): void {
this.name = name;
}
getEndpointId(): string {
return this.endpointId;
}
setDisplayCategory(category: DisplayCategory | DisplayCategory[]): void {
this.displayCategory = Array.isArray(category) ? category : [category];
}
getDisplayCategory(): Array<DisplayCategory> {
return this.displayCategory || [DisplayCategory.LIGHT];
}
setDescription(description: string): void {
this.description = description;
}
getDescription(): string {
return this.description;
}
getErrorMessage(correlationToken: string): AlexaErrorResponse {
const msg = new AlexaErrorResponse(
correlationToken,
this.rootTopic,
this.endpointId,
this.publisher
);
msg.onPublishError = this.onPublishError;
return msg;
}
getStatusMessage(
correlationToken: string,
isResponse = false,
isDeferred = false
): AlexaStatusMessage {
const msg = new AlexaStatusMessage(
correlationToken,
this.rootTopic,
this.endpointId,
this.publisher,
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.
* Without a changed property send() publishes nothing and resolves with "": Alex2MQTT would drop the report.
*/
getChangeReport(cause: ChangeCause = "PHYSICAL_INTERACTION"): AlexaStatusMessage {
const msg = new AlexaStatusMessage("", this.rootTopic, this.endpointId, this.publisher, 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: string, activated: boolean, cause: ChangeCause = "VOICE_INTERACTION", sendAsync = false): Promise<string> {
const answer = sendAsync ? topics.deferred : topics.response;
const build = () => sceneEvent({ endpointId: this.endpointId, correlationToken, activated, cause });
return send(this.publisher, answer(this.rootTopic, this.endpointId), build, this.onPublishError);
}
/**
* Say that something happened on the device, which nobody asked for:
*
* door.raise(DoorbellEventSource, "DoorbellPress");
* remote.raise(SimpleEventSource, "Event", { id: "Button.SinglePush.1" }, { instance: topButton.instance });
*
* The event goes to <root>/event, which Alex2MQTT posts to Alexa: up to 30 events a minute for a root. The
* payload is checked by the descriptor, which also sets the time of the event to now and its cause to the usual
* one when the payload has none. Resolves with what became of the publish and does not reject.
*
* Throws a MessageError for an event that would not arrive: of an interface or an instance the device did not
* declare, not an event of the interface, with a payload that does not fit, or too long for Alex2MQTT.
*/
raise(
descriptor: InterfaceDescriptor<any, any, any, boolean>,
name: string,
payload: Record<string, unknown> = {},
options: { instance?: string; messageId?: string } = {}
): Promise<PublishResult> {
const { endpointId } = this;
const { namespace } = descriptor;
const { instance = "", messageId } = options;
const refuse = (problem: string): never => {
throw new MessageError(endpointId, `${namespace}.${name} was not raised: ${problem}`);
};
const capability = this.capability(namespace, instance);
if (!capability) {
const declared = instance ? `the instance ${JSON.stringify(instance)} of ${namespace}` : namespace;
return refuse(`the device did not declare ${declared}. Declare it with add() first${descriptor.instanced && !instance ? ", and pass the instance that raises the event" : ""}`);
}
const events = capability.descriptor.events ?? {};
const event = events[name];
if (!event) return refuse(`it is not an event of the interface, which has ${Object.keys(events).join(", ") || "none"}`);
if (event.topic !== "proactive") return refuse("it answers a directive. Send it with respond() in the handler of the directive");
let checked: Record<string, unknown>;
try {
checked = event.payload.parse(payload, "payload");
} catch (err) {
if (err instanceof SchemaError) return refuse(err.message);
throw err;
}
const message = proactiveEvent({
endpointId,
messageId,
namespace: event.namespace ?? namespace,
name,
instance,
payloadVersion: event.payloadVersion ?? capability.descriptor.version,
payload: checked,
emptyContext: event.emptyContext,
});
const bytes = Buffer.byteLength(JSON.stringify(message));
if (bytes > topics.EVENT_BYTES) return refuse(`it is ${bytes} bytes as JSON, Alex2MQTT takes ${topics.EVENT_BYTES}`);
return this.publish(topics.event(this.rootTopic), message);
}
/**
* Say that the state of the device changed, without a directive that asked for it:
*
* door.changeReport("PHYSICAL_INTERACTION", (s) => s.set(contact, "detectionState", "DETECTED"));
*
* fill sets what changed; after unchanged() it sets what did not. The rest of the context is the state of
* device.state(). The report goes to <root>/changeReport, which Alex2MQTT posts to Alexa; Alexa takes it for a
* capability declared with proactivelyReported. Resolves with what became of the publish and does not reject.
*
* Throws a MessageError when fill sets no property that changed, and a SchemaError for a value Alexa would not take.
*/
changeReport(cause: ChangeCause, fill: Fill): Promise<PublishResult> {
const { endpointId } = this;
const own = new StateBuilder({ target: "change" });
fill(own);
const whole = new StateBuilder();
this.stateProvider?.(whole);
const context = [...whole.context.filter((property) => !own.context.some((other) => sameProperty(property, other))), ...own.context];
const message = changeReport({ endpointId, cause, changed: own.change, context });
return this.publish(topics.changeReport(this.rootTopic), message);
}
// A message nobody asked for: a failed publish is reported to the bridge and is the result
private publish(topic: string, message: object): Promise<PublishResult> {
const unpublished = new Error(`nothing was published to ${topic}: the device is on no bridge, register it with addDevice() or registerDevice()`);
const published: Promise<PublishResult> = this.publisher
? this.publisher.publish(topic, message)
: Promise.resolve({ ok: false, topic, error: unpublished });
return published.then((result) => {
if (!result.ok) this.onPublishError?.(result.error);
return result;
});
}
/**
* How the device reports its state, every retrievable property of it:
*
* blinds.state((s) => s.set(lift, "rangeValue", motor.position).health("OK"));
*
* ReportState is answered with it, and it is the context of every ctx.respond(), where the handler sets only what
* the directive changed. Alexa wants the whole state in both (alexa-response.html, "Synchronous response").
*/
state(fill: Fill): this {
this.stateProvider = fill;
return this;
}
/** Answer ReportState in a handler of its own, for a state that has to be read from the device first. */
onReportState(handler: DirectiveHandler<Record<string, never>>): this {
this.reportStateHandler = handler;
return this;
}
/** The handler for the directives of declared capabilities that have no handler of their own. */
onDirective(handler: DirectiveHandler): this {
this.directiveHandler = handler;
return this;
}
/** The capability declared for the interface, under the instance for a generic controller. */
capability(namespace: string, instance = ""): AnyCapability | undefined {
return this.capabilities.find((capability) => capability.namespace === namespace && capability.instance === instance);
}
/** The capabilities the device declared, in the order it declared them. */
getCapabilities(): AnyCapability[] {
return this.capabilities.slice();
}
setManufacturerName(name: string): void {
this.manufacturerName = name;
}
getManufacturerName(): string {
return this.manufacturerName;
}
setManufacturer(manufacturer: string): void {
this.manufacturer = manufacturer;
}
getManufacturer(): string {
return this.manufacturer;
}
setModel(model: string): void {
this.model = model;
}
getModel(): string {
return this.model;
}
getSoftwareVersion(): string {
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<P extends Properties, D extends Directives, O, I extends boolean>(
descriptor: InterfaceDescriptor<P, D, O, I>,
...[options]: DeclarationArguments<O, I>
): Capability<P, D, O> {
const where = { endpointId: this.endpointId, namespace: descriptor.namespace, instance: "" };
if (options !== undefined && (typeof options !== "object" || options === null)) {
throw new DeclarationError(where, "the options of a declaration are an object");
}
try {
const { instance, friendlyNames, retrievable, proactivelyReported, nonControllable, ...given } = commonOptions.parse(options ?? {});
where.instance = instance ?? "";
const common = { instance, friendlyNames: friendlyNames as Label[] | undefined, retrievable, proactivelyReported, nonControllable };
const capability = new Capability(descriptor, { ...common, options: interfaceOptions(descriptor, given) });
capability.endpointId = this.endpointId;
checkCapability(capability, descriptor, this.view(this.capabilities));
checkCapabilityCount(this.endpointId, this.announced([...this.capabilities, capability]).length);
this.capabilities.push(capability);
return capability;
} catch (err) {
throw err instanceof SchemaError ? new 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: AlexaInterfaceType | string, options: { retrievable?: boolean; proactivelyReported?: boolean; instance?: string } = {}): AlexaInterface {
let capability: AlexaInterface;
try {
capability = new AlexaInterface(type, options.retrievable ?? true, options.proactivelyReported ?? false, options.instance ?? "");
} catch (err) {
throw err instanceof DeclarationError ? new 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(): string[] {
const lines: string[] = [];
const attempt = (rule: () => void): void => {
try {
rule();
} catch (err) {
if (!(err instanceof DeclarationError)) throw err;
lines.push(err.message);
}
};
attempt(() => checkEndpoint(this.fields()));
this.capabilities.forEach((capability, i) => {
capability.endpointId = this.endpointId;
attempt(() => 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 DeclarationError(capability, note).message);
});
attempt(() => checkCapabilityCount(this.endpointId, this.announced(this.capabilities).length));
return lines;
}
/** The endpoint object for discovery. */
getJSON(): EndpointJson {
return { ...this.fields(), capabilities: this.announced(this.capabilities).map((capability) => capability.toJSON()) };
}
private fields(): EndpointFields {
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
private view(declaredBefore: readonly AnyCapability[]): EndpointView {
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
private announced(declared: readonly AnyCapability[]): AnyCapability[] {
const has = (namespace: string): boolean => declared.some((capability) => capability.namespace === namespace);
const added: AnyCapability[] = [];
// alexa-scenecontroller.html, "Discovery": a scene is not a physical device and has no Alexa.EndpointHealth
if (this.endpointHealth && !has(EndpointHealth.namespace) && !has(SceneController.namespace)) {
added.push(new Capability(EndpointHealth, { options: {} }));
}
if (this.alexaInterface && !has(Alexa.namespace)) added.push(new Capability(Alexa, { options: {} }));
return [...declared, ...added];
}
}
// The options of the interface itself, checked by the schema of its descriptor
function interfaceOptions<O>(descriptor: InterfaceDescriptor<any, any, O, boolean>, given: Record<string, unknown>): O {
if (descriptor.options) return descriptor.options.parse(given);
const [unknown] = Object.keys(given);
if (unknown !== undefined) throw new SchemaError(unknown, "not an option of the interface");
return {} as O;
}
export default Device;