Alex2Node/src/AlexaStatusMessage.ts
David c492ef74d1 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>
2026-09-28 15:35:46 +00:00

298 lines
8.5 KiB
TypeScript

import { randomUUID } from "crypto";
import { AlexaInterfaceType } from "./compat/enums.js";
import type { EndpointHealth, PowerController } from "./compat/enums.js";
import type { MqttClient } from "mqtt";
export enum ThermostatMode {
OFF = "OFF",
HEAT = "HEAT",
COOL = "COOL",
AUTO = "AUTO",
ECO = "ECO",
CUSTOM = "CUSTOM",
}
export enum TemperatureSensorScale {
CELSIUS = "CELSIUS",
FAHRENHEIT = "FAHRENHEIT",
}
interface DirectiveHeader {
namespace: string;
name: string;
payloadVersion: string;
messageId: string;
correlationToken: string;
}
interface DirectiveEndpoint {
endpointId: string;
}
interface ContextProperty {
namespace: string;
name: string;
value: any;
timeOfSample: string;
uncertaintyInMilliseconds: number;
instance?: string;
}
/** Why a ChangeReport is sent (Alexa.ChangeReport payload.change.cause.type). */
export type ChangeCause = "APP_INTERACTION" | "PHYSICAL_INTERACTION" | "PERIODIC_POLL" | "RULE_TRIGGER" | "VOICE_INTERACTION";
export class AlexaStatusMessage {
private context: { properties: ContextProperty[] } = { properties: [] };
/** ChangeReport only: the properties that changed (payload.change.properties); the rest go to context. */
private changeProps: ContextProperty[] = [];
private changeCause: ChangeCause | null = null;
private target: "context" | "change" = "context";
private event: {
header: DirectiveHeader;
endpoint: DirectiveEndpoint;
payload: {};
};
private rootTopic: string;
private endpointId: string;
private mqttClient: MqttClient;
private isDeferred: boolean;
/** Where a failed publish is reported (set by the Device that built this message, 1.5.2): send() never rejects. */
public onPublishError?: (err: Error) => void;
constructor(
correlationToken: string,
rootTopic: string,
endpointId: string,
mqttClient: MqttClient,
isResponse: boolean = false,
isDeferred: boolean = false,
changeCause: ChangeCause | null = null
) {
this.rootTopic = rootTopic;
this.endpointId = endpointId;
this.mqttClient = mqttClient;
this.isDeferred = isDeferred;
this.changeCause = changeCause;
if (changeCause) this.target = "change";
this.event = {
header: {
namespace: "Alexa",
name: changeCause
? "ChangeReport"
: isDeferred
? "DeferredResponse"
: isResponse
? "Response"
: "StateReport",
payloadVersion: "3",
messageId: randomUUID(),
correlationToken,
},
endpoint: {
endpointId,
},
payload: {},
};
}
private getTimestamp(): string {
return new Date().toISOString();
}
private addProperty(
namespace: AlexaInterfaceType,
name: string,
value: any,
uncertaintyInMilliseconds = 0,
instance?: string
): this {
const prop: ContextProperty = {
namespace,
name,
value,
timeOfSample: this.getTimestamp(),
uncertaintyInMilliseconds,
};
if (instance) prop.instance = instance;
(this.target === "change" ? this.changeProps : this.context.properties).push(prop);
return this;
}
/** ChangeReport: the add*Prop calls that follow describe what CHANGED (the default for a change report). */
public changed(): this {
this.target = "change";
return this;
}
/** ChangeReport: the add*Prop calls that follow describe the other, unchanged properties (context). */
public unchanged(): this {
this.target = "context";
return this;
}
/** True for a ChangeReport (Device.getChangeReport). */
public isChangeReport(): boolean {
return this.changeCause !== null;
}
/** The message as it will be published (for tests and logging). */
public toJSON(): { event: any; context: { properties: ContextProperty[] } | null } {
if (this.changeCause) {
return {
event: { ...this.event, payload: { change: { cause: { type: this.changeCause }, properties: this.changeProps } } },
context: this.context,
};
}
return { context: this.isDeferred ? null : this.context, event: this.event };
}
public addModeControllerProp(instance: string, value: string, uncertaintyInMs = 0): this {
return this.addProperty(
AlexaInterfaceType.MODE_CONTROLLER,
"mode",
value,
uncertaintyInMs,
instance
);
}
public addThermostatModeProp(mode: string, uncertaintyInMs = 0): this {
return this.addProperty(
AlexaInterfaceType.THERMOSTAT_CONTROLLER,
"thermostatMode",
mode,
uncertaintyInMs
);
}
public addEstimatedDeferralTime(seconds: number): this {
if (this.isDeferred) {
this.event.payload = {
estimatedDeferralInSeconds: seconds,
};
} else {
console.warn(
"[AlexaStatusMessage.ts] Attempted to add estimated deferral time, but message is not marked as DeferredResponse."
);
}
return this;
}
public addThermostatControllerProp(
name: "lowerSetpoint" | "upperSetpoint" | "targetSetpoint",
scale: TemperatureSensorScale,
value: number,
uncertaintyInMs = 0
): this {
const tempValue = {
value:
scale === TemperatureSensorScale.FAHRENHEIT
? (value - 32) * (5 / 9)
: value,
scale: "CELSIUS",
};
return this.addProperty(
AlexaInterfaceType.THERMOSTAT_CONTROLLER,
name,
tempValue,
uncertaintyInMs
);
}
/** Alexa.EndpointHealth connectivity: EndpointHealth.OK / UNREACHABLE (the plain strings "OK" / "UNREACHABLE" are accepted too). */
public addHealthProp(health: EndpointHealth | `${EndpointHealth}`, uncertaintyInMs = 0): this {
return this.addProperty(
AlexaInterfaceType.ENDPOINT_HEALTH,
"connectivity",
{ value: health },
uncertaintyInMs
);
}
public addPowerControllerProp(
power: PowerController,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.POWER_CONTROLLER,
"powerState",
power,
uncertaintyInMs
);
}
public addTemperatureSensorProp(
scale: TemperatureSensorScale,
value: number,
uncertaintyInMs = 0
): this {
const tempValue = {
value:
scale === TemperatureSensorScale.FAHRENHEIT
? (value - 32) * (5 / 9)
: value,
scale: "CELSIUS",
};
return this.addProperty(
AlexaInterfaceType.TEMPERATURE_SENSOR,
"temperature",
tempValue,
uncertaintyInMs
);
}
public addBrightnessControllerProp(
brightness: number,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.BRIGHTNESS_CONTROLLER,
"brightness",
brightness,
uncertaintyInMs
);
}
public addColorTemperatureControllerProp(
colorTemp: number,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.COLOR_TEMPERATURE_CONTROLLER,
"colorTemperatureInKelvin",
colorTemp,
uncertaintyInMs
);
}
public addToggleControllerProp(
state: PowerController,
instance: string,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.TOGGLE_CONTROLLER,
"toggleState",
state,
uncertaintyInMs,
instance
);
}
public addContextProp(prop: ContextProperty): this {
this.context.properties.push(prop);
return this;
}
/**
* Publish: a Response/StateReport to <root>/<endpoint>/alexaResponce (sendAsync: deferredResponse), a ChangeReport
* to <root>/changeReport (Alex2MQTT adds the user's token and posts it to the Alexa event gateway). Resolves with
* the topic, or "" when the publish failed - the error then goes to the bridge's "error" event (when listened to).
* Never rejects (1.5.1 did, so an un-caught send() could kill the host).
*/
public send(sendAsync: boolean = false): Promise<string> {
const payloadStr = JSON.stringify(this.toJSON());
const topic = this.changeCause
? `${this.rootTopic}/changeReport`
: `${this.rootTopic}/${this.endpointId}/${sendAsync ? "deferredResponse" : "alexaResponce"}`; //Yes this should be response but it is incorrect in both Alex2MQTT and Alex2ESP so for consistency is is wrong here too
return new Promise((resolve) => {
this.mqttClient.publish(topic, payloadStr, (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
});
});
}
}