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
|
|
@ -1,41 +0,0 @@
|
|||
export enum AlexaActions {
|
||||
Open = "Alexa.Actions.Open",
|
||||
Close = "Alexa.Actions.Close",
|
||||
Raise = "Alexa.Actions.Raise",
|
||||
Lower = "Alexa.Actions.Lower",
|
||||
SetEcoOn = "Alexa.Actions.SetEcoOn",
|
||||
SetEcoOff = "Alexa.Actions.SetEcoOff",
|
||||
}
|
||||
|
||||
interface Directive {
|
||||
name: string;
|
||||
payload?: string;
|
||||
}
|
||||
|
||||
export class ActionMapping {
|
||||
type: string = "ActionsToDirective";
|
||||
actions: AlexaActions[];
|
||||
directive: Directive;
|
||||
|
||||
constructor(
|
||||
actions: AlexaActions[],
|
||||
directiveName: string,
|
||||
directivePayload?: string
|
||||
) {
|
||||
this.actions = actions;
|
||||
this.directive = {
|
||||
name: directiveName,
|
||||
};
|
||||
if (directivePayload) {
|
||||
this.directive.payload = directivePayload;
|
||||
}
|
||||
}
|
||||
|
||||
toJSON(): object {
|
||||
return {
|
||||
"@type": this.type,
|
||||
actions: this.actions,
|
||||
directive: this.directive,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,10 +1,12 @@
|
|||
// mqtt reaches Node as CommonJS: the default import works from both builds, a named one needs Node to detect it.
|
||||
import mqtt from "mqtt";
|
||||
import type { MqttClient, IClientOptions } from "mqtt";
|
||||
import Device from "./Device.js";
|
||||
import Device from "./device/Device.js";
|
||||
import type { EndpointDefinition, EndpointJson } from "./device/Device.js";
|
||||
import { checkEndpoint } from "./device/validate.js";
|
||||
import { EventEmitter } from "events";
|
||||
import { DisplayCategory } from "./DisplayCategory.js";
|
||||
import { AlexaInterfaceType } from "./AlexaInterface.js";
|
||||
import { DisplayCategory } from "./compat/enums.js";
|
||||
import { DeclarationError } from "./registry/types.js";
|
||||
|
||||
/** Optional settings for the bridge (1.5.1). Everything has the 1.4.0 behaviour as its default. */
|
||||
export interface Alex2MQTTOptions {
|
||||
|
|
@ -14,10 +16,21 @@ export interface Alex2MQTTOptions {
|
|||
mqtt?: IClientOptions;
|
||||
/** Where log lines go. Default: console (only when debugLogging is on). */
|
||||
log?: (message: string, detail?: unknown) => void;
|
||||
/**
|
||||
* false: discovery does not list the Alexa interface on the endpoints. Default: every endpoint ends with
|
||||
* { type: "AlexaInterface", interface: "Alexa", version: "3" }, which Amazon requires and 1.x left out.
|
||||
*/
|
||||
alexaInterface?: boolean;
|
||||
}
|
||||
|
||||
export const 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.
|
||||
|
|
@ -37,6 +50,8 @@ class Alex2MQTT extends EventEmitter {
|
|||
private devices: Device[] = [];
|
||||
private MqttHost: string;
|
||||
private options: Alex2MQTTOptions;
|
||||
// The lines of check() that were logged. Discovery comes every few minutes: a line is logged once.
|
||||
private logged = new Set<string>();
|
||||
/** true while the broker connection is up. */
|
||||
public connected = false;
|
||||
/** ISO time of the last discovery request answered, null before the first. */
|
||||
|
|
@ -98,12 +113,8 @@ class Alex2MQTT extends 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() !== 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); return; }
|
||||
this.log(`Discovery payloads published to ${topic + "_r"}`, deviceArray);
|
||||
|
|
@ -138,6 +149,25 @@ class Alex2MQTT extends 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.
|
||||
private describeDevices(): EndpointJson[] {
|
||||
const endpoints: EndpointJson[] = [];
|
||||
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(): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
|
|
@ -149,10 +179,38 @@ class Alex2MQTT extends EventEmitter {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: EndpointDefinition): Device {
|
||||
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(this.client, this.rootTopic, name, endpointId, (categories ?? []) as DisplayCategory[]);
|
||||
for (const [field, value] of Object.entries(described)) {
|
||||
if (!DESCRIBED.includes(field)) throw new DeclarationError({ endpointId }, `${field} is not a field of an endpoint`);
|
||||
if (value !== undefined) Object.assign(device, { [field]: value });
|
||||
}
|
||||
checkEndpoint(device.getJSON());
|
||||
const existing = this.getDevice(endpointId);
|
||||
if (existing) throw new DeclarationError({ endpointId }, `is registered already, as "${existing.name}"`);
|
||||
this.register(device, endpointHealth !== false);
|
||||
return device;
|
||||
}
|
||||
|
||||
registerDevice(
|
||||
name: string,
|
||||
endpointId: string,
|
||||
displayCategory: DisplayCategory | DisplayCategory[] | null
|
||||
displayCategory?: DisplayCategory | DisplayCategory[] | null
|
||||
): Device {
|
||||
if (!this.client) {
|
||||
throw new Error("Must call connect before creating devices");
|
||||
|
|
@ -164,23 +222,17 @@ class Alex2MQTT extends EventEmitter {
|
|||
return existing;
|
||||
}
|
||||
this.log(`Creating new device with endpoint: ${endpointId}`);
|
||||
const normalizedCategory =
|
||||
displayCategory === null
|
||||
? [DisplayCategory.LIGHT]
|
||||
: Array.isArray(displayCategory)
|
||||
? displayCategory
|
||||
: [displayCategory || DisplayCategory.LIGHT];
|
||||
const normalizedCategory = Array.isArray(displayCategory) ? displayCategory : [displayCategory || DisplayCategory.LIGHT];
|
||||
const device = new Device(this.client, this.rootTopic, name, endpointId, normalizedCategory);
|
||||
this.register(device, false);
|
||||
return device;
|
||||
}
|
||||
|
||||
const device = new Device(
|
||||
this.client!,
|
||||
this.rootTopic,
|
||||
name,
|
||||
endpointId,
|
||||
normalizedCategory
|
||||
);
|
||||
private register(device: Device, endpointHealth: boolean): void {
|
||||
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. */
|
||||
|
|
|
|||
|
|
@ -1,12 +1,8 @@
|
|||
import { randomUUID } from "crypto";
|
||||
import { AlexaInterfaceType } from "./AlexaInterface.js";
|
||||
import { AlexaInterfaceType } from "./compat/enums.js";
|
||||
import type { EndpointHealth, PowerController } from "./compat/enums.js";
|
||||
import type { MqttClient } from "mqtt";
|
||||
|
||||
export enum EndpointHealth {
|
||||
OK = "OK",
|
||||
UNREACHABLE = "UNREACHABLE",
|
||||
}
|
||||
|
||||
export enum ThermostatMode {
|
||||
OFF = "OFF",
|
||||
HEAT = "HEAT",
|
||||
|
|
@ -16,11 +12,6 @@ export enum ThermostatMode {
|
|||
CUSTOM = "CUSTOM",
|
||||
}
|
||||
|
||||
export enum PowerController {
|
||||
ON = "ON",
|
||||
OFF = "OFF",
|
||||
}
|
||||
|
||||
export enum TemperatureSensorScale {
|
||||
CELSIUS = "CELSIUS",
|
||||
FAHRENHEIT = "FAHRENHEIT",
|
||||
|
|
|
|||
182
src/Device.ts
182
src/Device.ts
|
|
@ -1,182 +0,0 @@
|
|||
import { AlexaInterface } from "./AlexaInterface.js";
|
||||
import type { AlexaInterfaceType } from "./AlexaInterface.js";
|
||||
import { DisplayCategory } from "./DisplayCategory.js";
|
||||
import { EventEmitter } from "events";
|
||||
import { randomUUID } from "crypto";
|
||||
import type { MqttClient } from "mqtt";
|
||||
import { AlexaStatusMessage } from "./AlexaStatusMessage.js";
|
||||
import type { ChangeCause } from "./AlexaStatusMessage.js";
|
||||
import { AlexaErrorResponse } from "./AlexaErrorResponse.js";
|
||||
|
||||
class Device extends EventEmitter {
|
||||
protected softwareVersion: string = "1.0.0";
|
||||
private capabilities: AlexaInterface[] = [];
|
||||
/** 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;
|
||||
|
||||
constructor(
|
||||
private mqttClient: MqttClient,
|
||||
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();
|
||||
}
|
||||
|
||||
/** Internal (1.5.2): Alex2MQTT.connect() re-binds every registered device to its new broker client after a disconnect(). */
|
||||
setMqttClient(client: MqttClient): void {
|
||||
this.mqttClient = client;
|
||||
}
|
||||
|
||||
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.mqttClient
|
||||
);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
getStatusMessage(
|
||||
correlationToken: string,
|
||||
isResponse = false,
|
||||
isDeferred = false
|
||||
): AlexaStatusMessage {
|
||||
const msg = new 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: ChangeCause = "PHYSICAL_INTERACTION"): AlexaStatusMessage {
|
||||
const msg = new 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: string, activated: boolean, cause: ChangeCause = "VOICE_INTERACTION", sendAsync = false): Promise<string> {
|
||||
const payload = {
|
||||
context: {},
|
||||
event: {
|
||||
header: { namespace: "Alexa.SceneController", name: activated ? "ActivationStarted" : "DeactivationStarted", messageId: 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(): AlexaInterface[] {
|
||||
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;
|
||||
}
|
||||
|
||||
/** Add a capability. 1.5.1: options.retrievable / proactivelyReported / instance (a change report needs proactivelyReported). */
|
||||
addCapability(type: AlexaInterfaceType, options: { retrievable?: boolean; proactivelyReported?: boolean; instance?: string } = {}): AlexaInterface {
|
||||
const newCapability = new 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(): Record<string, any> {
|
||||
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()),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export default Device;
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
export enum DisplayCategory {
|
||||
ACTIVITY_TRIGGER = "ACTIVITY_TRIGGER",
|
||||
AIR_CONDITIONER = "AIR_CONDITIONER",
|
||||
AIR_FRESHENER = "AIR_FRESHENER",
|
||||
AIR_PURIFIER = "AIR_PURIFIER",
|
||||
AIR_QUALITY_MONITOR = "AIR_QUALITY_MONITOR",
|
||||
ALEXA_VOICE_ENABLED = "ALEXA_VOICE_ENABLED",
|
||||
AUTO_ACCESSORY = "AUTO_ACCESSORY",
|
||||
BLUETOOTH_SPEAKER = "BLUETOOTH_SPEAKER",
|
||||
CAMERA = "CAMERA",
|
||||
CHRISTMAS_TREE = "CHRISTMAS_TREE",
|
||||
COFFEE_MAKER = "COFFEE_MAKER",
|
||||
COMPUTER = "COMPUTER",
|
||||
CONTACT_SENSOR = "CONTACT_SENSOR",
|
||||
DISHWASHER = "DISHWASHER",
|
||||
DOOR = "DOOR",
|
||||
DOORBELL = "DOORBELL",
|
||||
DRYER = "DRYER",
|
||||
EXTERIOR_BLIND = "EXTERIOR_BLIND",
|
||||
FAN = "FAN",
|
||||
GAME_CONSOLE = "GAME_CONSOLE",
|
||||
GARAGE_DOOR = "GARAGE_DOOR",
|
||||
HEADPHONES = "HEADPHONES",
|
||||
HUB = "HUB",
|
||||
INTERIOR_BLIND = "INTERIOR_BLIND",
|
||||
LAPTOP = "LAPTOP",
|
||||
LIGHT = "LIGHT",
|
||||
MICROWAVE = "MICROWAVE",
|
||||
MOBILE_PHONE = "MOBILE_PHONE",
|
||||
MOTION_SENSOR = "MOTION_SENSOR",
|
||||
MUSIC_SYSTEM = "MUSIC_SYSTEM",
|
||||
NETWORK_HARDWARE = "NETWORK_HARDWARE",
|
||||
OTHER = "OTHER",
|
||||
OVEN = "OVEN",
|
||||
PHONE = "PHONE",
|
||||
PRINTER = "PRINTER",
|
||||
REMOTE = "REMOTE",
|
||||
ROUTER = "ROUTER",
|
||||
SCENE_TRIGGER = "SCENE_TRIGGER",
|
||||
SCREEN = "SCREEN",
|
||||
SECURITY_PANEL = "SECURITY_PANEL",
|
||||
SECURITY_SYSTEM = "SECURITY_SYSTEM",
|
||||
SLOW_COOKER = "SLOW_COOKER",
|
||||
SMARTLOCK = "SMARTLOCK",
|
||||
SMARTPLUG = "SMARTPLUG",
|
||||
SPEAKER = "SPEAKER",
|
||||
STREAMING_DEVICE = "STREAMING_DEVICE",
|
||||
SWITCH = "SWITCH",
|
||||
TABLET = "TABLET",
|
||||
TEMPERATURE_SENSOR = "TEMPERATURE_SENSOR",
|
||||
THERMOSTAT = "THERMOSTAT",
|
||||
TV = "TV",
|
||||
VACUUM_CLEANER = "VACUUM_CLEANER",
|
||||
VACUUM = "VACUUM",
|
||||
/** Not on the list of display categories any more; kept for 1.x callers. */
|
||||
VEHICLE = "VEHICLE",
|
||||
WASHER = "WASHER",
|
||||
WATER_HEATER = "WATER_HEATER",
|
||||
WEARABLE = "WEARABLE",
|
||||
}
|
||||
52
src/compat/ActionMapping.ts
Normal file
52
src/compat/ActionMapping.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { DeclarationError } from "../registry/types.js";
|
||||
import type { ActionsToDirective } from "../registry/types.js";
|
||||
import type { AlexaActions } from "./enums.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 }));
|
||||
*/
|
||||
export class ActionMapping {
|
||||
type = "ActionsToDirective" as const;
|
||||
actions: AlexaActions[];
|
||||
directive: ActionsToDirective["directive"];
|
||||
/** Set when the mapping was built in a way that 3.0 will refuse; the bridge logs it at the next discovery. */
|
||||
readonly deprecation?: string;
|
||||
|
||||
/**
|
||||
* 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: AlexaActions[], directiveName: string, directivePayload?: Record<string, unknown> | string) {
|
||||
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(): ActionsToDirective {
|
||||
return { "@type": this.type, actions: this.actions, directive: this.directive };
|
||||
}
|
||||
}
|
||||
|
||||
function objectIn(text: string, directiveName: string): Record<string, unknown> {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(text);
|
||||
} catch {
|
||||
value = undefined;
|
||||
}
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||
throw new DeclarationError({}, `the payload of the action mapping for ${directiveName} is an object, got the string ${JSON.stringify(text)}`);
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
82
src/compat/AlexaInterface.ts
Normal file
82
src/compat/AlexaInterface.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { Capability } from "../device/Capability.js";
|
||||
import type { CapabilityJson } from "../device/Capability.js";
|
||||
import { registry } from "../registry/index.js";
|
||||
import { text } from "../registry/resources.js";
|
||||
import type { Semantics } from "../registry/types.js";
|
||||
import type { ActionMapping } from "./ActionMapping.js";
|
||||
import type { AlexaInterfaceType } from "./enums.js";
|
||||
|
||||
/** One ModeController mode as discovery lists it (configuration.supportedModes): the value plus its friendly names. */
|
||||
export interface SupportedMode {
|
||||
value: string;
|
||||
modeResources?: { friendlyNames: Array<{ "@type": string; value: { text?: string; locale?: string; assetId?: string } }> };
|
||||
}
|
||||
|
||||
interface Options {
|
||||
semantics?: Semantics;
|
||||
supportedModes?: Array<string | SupportedMode>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export class AlexaInterface extends Capability<any, any, Options> {
|
||||
constructor(type: AlexaInterfaceType | string, retrievable = true, proactivelyReported = false, instance = "") {
|
||||
super(registry.get(type), { retrievable, proactivelyReported, instance, options: {} });
|
||||
}
|
||||
|
||||
/** The namespace of the interface, which is the value of its AlexaInterfaceType member. */
|
||||
get type(): AlexaInterfaceType {
|
||||
return this.descriptor.namespace as AlexaInterfaceType;
|
||||
}
|
||||
|
||||
addActionMapping(mapping: ActionMapping): void {
|
||||
const semantics = (this.options.semantics ??= {});
|
||||
(semantics.actionMappings ??= []).push(mapping.toJSON());
|
||||
if (mapping.deprecation) this.notes.push(mapping.deprecation);
|
||||
}
|
||||
|
||||
addFriendlyName(name: string, locale: string): void {
|
||||
this.friendlyNames.push(text(name, locale));
|
||||
}
|
||||
|
||||
/** The modes of a ModeController, as { value, modeResources } objects. */
|
||||
addSupportedModes(modes: Array<string | SupportedMode>): void {
|
||||
this.options.supportedModes = modes;
|
||||
}
|
||||
|
||||
setInstance(name: string): void {
|
||||
this.instance = name;
|
||||
}
|
||||
|
||||
getType(): AlexaInterfaceType {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
/** @deprecated The same as getType(). */
|
||||
getTypeString(): string {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
/** @deprecated Read descriptor.version. */
|
||||
getVersion(): string {
|
||||
return this.descriptor.version;
|
||||
}
|
||||
|
||||
/** @deprecated Read the keys of descriptor.properties. */
|
||||
getProps(): string[] {
|
||||
return Object.keys(this.descriptor.properties);
|
||||
}
|
||||
|
||||
getJSON(): CapabilityJson {
|
||||
return super.toJSON();
|
||||
}
|
||||
|
||||
// 1.x callers corrected the discovery JSON by replacing getJSON on the object: discovery goes through it
|
||||
toJSON(): CapabilityJson {
|
||||
return this.getJSON();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import type { ActionMapping } from "./ActionMapping.js";
|
||||
import { registry } from "./registry/index.js";
|
||||
// The enums of 1.x, under their 1.x names.
|
||||
import { EndpointHealth as EndpointHealthInterface } from "../registry/interfaces/EndpointHealth.js";
|
||||
import { PowerController as PowerControllerInterface } from "../registry/interfaces/PowerController.js";
|
||||
|
||||
/** Every interface name of 1.x. registry.get() takes a member as it takes the namespace, which is its value. */
|
||||
export enum AlexaInterfaceType {
|
||||
APPLICATION_STATE_REPORTER = "Alexa.ApplicationStateReporter",
|
||||
AUDIO_PLAY_QUEUE = "Alexa.Audio.PlayQueue",
|
||||
|
|
@ -71,115 +73,96 @@ export enum AlexaInterfaceType {
|
|||
USER_PREFERENCE = "Alexa.UserPreference",
|
||||
VIDEO_RECORDER = "Alexa.VideoRecorder",
|
||||
WAKE_ON_LAN_CONTROLLER = "Alexa.WakeOnLANController",
|
||||
/** Not an interface: declaring it throws a DeclarationError. Kept because 1.x had it. */
|
||||
UNKNOWN = "UNKNOWN",
|
||||
}
|
||||
|
||||
interface FriendlyName {
|
||||
text: string;
|
||||
locale: string;
|
||||
export enum DisplayCategory {
|
||||
ACTIVITY_TRIGGER = "ACTIVITY_TRIGGER",
|
||||
AIR_CONDITIONER = "AIR_CONDITIONER",
|
||||
AIR_FRESHENER = "AIR_FRESHENER",
|
||||
AIR_PURIFIER = "AIR_PURIFIER",
|
||||
AIR_QUALITY_MONITOR = "AIR_QUALITY_MONITOR",
|
||||
ALEXA_VOICE_ENABLED = "ALEXA_VOICE_ENABLED",
|
||||
AUTO_ACCESSORY = "AUTO_ACCESSORY",
|
||||
BLUETOOTH_SPEAKER = "BLUETOOTH_SPEAKER",
|
||||
CAMERA = "CAMERA",
|
||||
CHRISTMAS_TREE = "CHRISTMAS_TREE",
|
||||
COFFEE_MAKER = "COFFEE_MAKER",
|
||||
COMPUTER = "COMPUTER",
|
||||
CONTACT_SENSOR = "CONTACT_SENSOR",
|
||||
DISHWASHER = "DISHWASHER",
|
||||
DOOR = "DOOR",
|
||||
DOORBELL = "DOORBELL",
|
||||
DRYER = "DRYER",
|
||||
EXTERIOR_BLIND = "EXTERIOR_BLIND",
|
||||
FAN = "FAN",
|
||||
GAME_CONSOLE = "GAME_CONSOLE",
|
||||
GARAGE_DOOR = "GARAGE_DOOR",
|
||||
HEADPHONES = "HEADPHONES",
|
||||
HUB = "HUB",
|
||||
INTERIOR_BLIND = "INTERIOR_BLIND",
|
||||
LAPTOP = "LAPTOP",
|
||||
LIGHT = "LIGHT",
|
||||
MICROWAVE = "MICROWAVE",
|
||||
MOBILE_PHONE = "MOBILE_PHONE",
|
||||
MOTION_SENSOR = "MOTION_SENSOR",
|
||||
MUSIC_SYSTEM = "MUSIC_SYSTEM",
|
||||
NETWORK_HARDWARE = "NETWORK_HARDWARE",
|
||||
OTHER = "OTHER",
|
||||
OVEN = "OVEN",
|
||||
PHONE = "PHONE",
|
||||
PRINTER = "PRINTER",
|
||||
REMOTE = "REMOTE",
|
||||
ROUTER = "ROUTER",
|
||||
SCENE_TRIGGER = "SCENE_TRIGGER",
|
||||
SCREEN = "SCREEN",
|
||||
SECURITY_PANEL = "SECURITY_PANEL",
|
||||
SECURITY_SYSTEM = "SECURITY_SYSTEM",
|
||||
SLOW_COOKER = "SLOW_COOKER",
|
||||
SMARTLOCK = "SMARTLOCK",
|
||||
SMARTPLUG = "SMARTPLUG",
|
||||
SPEAKER = "SPEAKER",
|
||||
STREAMING_DEVICE = "STREAMING_DEVICE",
|
||||
SWITCH = "SWITCH",
|
||||
TABLET = "TABLET",
|
||||
TEMPERATURE_SENSOR = "TEMPERATURE_SENSOR",
|
||||
THERMOSTAT = "THERMOSTAT",
|
||||
TV = "TV",
|
||||
VACUUM_CLEANER = "VACUUM_CLEANER",
|
||||
VACUUM = "VACUUM",
|
||||
/** Not on the list of display categories any more; kept for 1.x callers. */
|
||||
VEHICLE = "VEHICLE",
|
||||
WASHER = "WASHER",
|
||||
WATER_HEATER = "WATER_HEATER",
|
||||
WEARABLE = "WEARABLE",
|
||||
}
|
||||
|
||||
/** One ModeController mode as discovery lists it (configuration.supportedModes): the value plus its friendly names. */
|
||||
export interface SupportedMode {
|
||||
value: string;
|
||||
modeResources?: { friendlyNames: Array<{ "@type": string; value: { text?: string; locale?: string; assetId?: string } }> };
|
||||
export enum AlexaActions {
|
||||
Open = "Alexa.Actions.Open",
|
||||
Close = "Alexa.Actions.Close",
|
||||
Raise = "Alexa.Actions.Raise",
|
||||
Lower = "Alexa.Actions.Lower",
|
||||
SetEcoOn = "Alexa.Actions.SetEcoOn",
|
||||
SetEcoOff = "Alexa.Actions.SetEcoOff",
|
||||
}
|
||||
|
||||
export class AlexaInterface {
|
||||
private friendlyNames: FriendlyName[] = [];
|
||||
private actionMappings: ActionMapping[] = [];
|
||||
private supportedModes: Array<string | SupportedMode> = [];
|
||||
/** The values of powerState and toggleState. */
|
||||
export const PowerState = { ON: "ON", OFF: "OFF" } as const;
|
||||
export type PowerState = (typeof PowerState)[keyof typeof PowerState];
|
||||
|
||||
constructor(
|
||||
public type: AlexaInterfaceType,
|
||||
public retrievable: boolean = true,
|
||||
public proactivelyReported: boolean = false,
|
||||
public instance = ""
|
||||
) {}
|
||||
const Connectivity = { OK: "OK", UNREACHABLE: "UNREACHABLE" } as const;
|
||||
|
||||
addActionMapping(mapping: ActionMapping): void {
|
||||
this.actionMappings.push(mapping);
|
||||
}
|
||||
// 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.
|
||||
|
||||
addFriendlyName(name: string, locale: string): void {
|
||||
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: Array<string | SupportedMode>): void {
|
||||
this.supportedModes = modes;
|
||||
}
|
||||
setInstance(name: string): void {
|
||||
this.instance = name;
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export const PowerController = Object.assign(PowerControllerInterface, PowerState);
|
||||
export type PowerController = PowerState;
|
||||
|
||||
getType(): AlexaInterfaceType {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
getTypeString(): string {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
/** The version of the interface, from its descriptor. "UNKNOWN" for a name the registry does not have. */
|
||||
getVersion(): string {
|
||||
return registry.has(this.type) ? registry.get(this.type).version : "UNKNOWN";
|
||||
}
|
||||
|
||||
/** The names of the properties the interface reports, from its descriptor. */
|
||||
getProps(): string[] {
|
||||
return registry.has(this.type) ? Object.keys(registry.get(this.type).properties) : [];
|
||||
}
|
||||
|
||||
getJSON(): object {
|
||||
const doc: any = {
|
||||
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: any = { "@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;
|
||||
}
|
||||
}
|
||||
/** The Alexa.EndpointHealth interface, for device.add(). EndpointHealth.OK and EndpointHealth.UNREACHABLE are the 1.x enum of connectivity values. */
|
||||
export const EndpointHealth = Object.assign(EndpointHealthInterface, Connectivity);
|
||||
export type EndpointHealth = (typeof Connectivity)[keyof typeof Connectivity];
|
||||
116
src/device/Capability.ts
Normal file
116
src/device/Capability.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
import { s } from "../registry/schema.js";
|
||||
import type {
|
||||
Declared, Directives, InterfaceDescriptor, Label, Properties, Semantics,
|
||||
} from "../registry/types.js";
|
||||
|
||||
/** What a declaration can set for any interface. */
|
||||
export interface CommonOptions {
|
||||
/** The name of the instance of a generic controller: "Blind.Lift", "Fan.Speed". */
|
||||
instance?: string;
|
||||
/** What the user calls the instance; the first name is the one the Alexa app shows. */
|
||||
friendlyNames?: Label[];
|
||||
/** The properties are in the answer to ReportState. Default: true. */
|
||||
retrievable?: boolean;
|
||||
/** A change of the properties is sent to Alexa as a ChangeReport. Default: false. */
|
||||
proactivelyReported?: boolean;
|
||||
/** The user can ask for the properties and cannot set them. Left out of discovery when not given. */
|
||||
nonControllable?: boolean;
|
||||
}
|
||||
|
||||
/** The same as a schema. The friendly names are checked with the instance, by the rules of the interface. */
|
||||
export const commonOptions = s.object({
|
||||
instance: s.optional(s.string()),
|
||||
friendlyNames: s.optional(s.array(s.unknown())),
|
||||
retrievable: s.optional(s.boolean()),
|
||||
proactivelyReported: s.optional(s.boolean()),
|
||||
nonControllable: s.optional(s.boolean()),
|
||||
});
|
||||
|
||||
type Naming<I extends boolean> = I extends true
|
||||
? { instance: string; friendlyNames: Label[] }
|
||||
: { instance?: string; friendlyNames?: Label[] };
|
||||
|
||||
/** The options of device.add() for one interface: its own, and the ones every interface has. */
|
||||
export type Declaration<O, I extends boolean> = O & Omit<CommonOptions, "instance" | "friendlyNames"> & Naming<I>;
|
||||
|
||||
/** A capability object of a discovery answer (alexa-discovery-objects.html, "Capability object"). */
|
||||
export interface CapabilityJson {
|
||||
type: "AlexaInterface";
|
||||
interface: string;
|
||||
instance?: string;
|
||||
version: string;
|
||||
properties?: {
|
||||
supported: Array<{ name: string }>;
|
||||
proactivelyReported: boolean;
|
||||
retrievable: boolean;
|
||||
nonControllable?: boolean;
|
||||
};
|
||||
capabilityResources?: { friendlyNames: Label[] };
|
||||
configuration?: Record<string, unknown>;
|
||||
configurations?: Record<string, unknown>;
|
||||
semantics?: Semantics;
|
||||
[field: string]: unknown;
|
||||
}
|
||||
|
||||
/** One interface as an endpoint declares it: the descriptor, and what the declaration says about this endpoint. */
|
||||
export class Capability<P extends Properties = Properties, D extends Directives = Directives, O = {}> implements Declared<O> {
|
||||
/** The endpoint the capability is declared on; the device sets it. */
|
||||
endpointId = "";
|
||||
/** "" for an interface without instances. */
|
||||
instance: string;
|
||||
friendlyNames: Label[];
|
||||
retrievable: boolean;
|
||||
proactivelyReported: boolean;
|
||||
nonControllable?: boolean;
|
||||
/** The options of the interface: a range, the supported modes, the semantics. */
|
||||
options: O;
|
||||
/** What the bridge logs about the declaration, once, when it answers a discovery. */
|
||||
readonly notes: string[] = [];
|
||||
|
||||
constructor(readonly descriptor: InterfaceDescriptor<P, D, O, boolean>, declared: CommonOptions & { options: O }) {
|
||||
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(): string {
|
||||
return this.descriptor.namespace;
|
||||
}
|
||||
|
||||
/** Mappings of "open", "close", "raise", "lower" and of states, when the declaration has any. */
|
||||
get semantics(): Semantics | undefined {
|
||||
const { semantics } = this.options as { semantics?: Semantics };
|
||||
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(): CapabilityJson {
|
||||
const { descriptor, semantics } = this;
|
||||
const extras = descriptor.discovery ? descriptor.discovery(this) : {};
|
||||
const json: CapabilityJson = {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
||||
export type AnyCapability = Capability<any, any, any>;
|
||||
348
src/device/Device.ts
Normal file
348
src/device/Device.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
import { EventEmitter } from "events";
|
||||
import { randomUUID } from "crypto";
|
||||
import type { MqttClient } from "mqtt";
|
||||
import { AlexaErrorResponse } from "../AlexaErrorResponse.js";
|
||||
import { AlexaStatusMessage } from "../AlexaStatusMessage.js";
|
||||
import type { ChangeCause } from "../AlexaStatusMessage.js";
|
||||
import { AlexaInterface } from "../compat/AlexaInterface.js";
|
||||
import { DisplayCategory } from "../compat/enums.js";
|
||||
import type { AlexaInterfaceType } from "../compat/enums.js";
|
||||
import type { DisplayCategoryName } from "../registry/catalog.js";
|
||||
import { Alexa } from "../registry/interfaces/Alexa.js";
|
||||
import { EndpointHealth } from "../registry/interfaces/EndpointHealth.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 { 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>];
|
||||
|
||||
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;
|
||||
|
||||
constructor(
|
||||
private mqttClient: MqttClient,
|
||||
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();
|
||||
}
|
||||
|
||||
/** Internal (1.5.2): Alex2MQTT.connect() re-binds every registered device to its new broker client after a disconnect(). */
|
||||
setMqttClient(client: MqttClient): void {
|
||||
this.mqttClient = client;
|
||||
}
|
||||
|
||||
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.mqttClient
|
||||
);
|
||||
msg.onPublishError = this.onPublishError;
|
||||
return msg;
|
||||
}
|
||||
getStatusMessage(
|
||||
correlationToken: string,
|
||||
isResponse = false,
|
||||
isDeferred = false
|
||||
): AlexaStatusMessage {
|
||||
const msg = new 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: ChangeCause = "PHYSICAL_INTERACTION"): AlexaStatusMessage {
|
||||
const msg = new 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: string, activated: boolean, cause: ChangeCause = "VOICE_INTERACTION", sendAsync = false): Promise<string> {
|
||||
const payload = {
|
||||
context: {},
|
||||
event: {
|
||||
header: { namespace: "Alexa.SceneController", name: activated ? "ActivationStarted" : "DeactivationStarted", messageId: 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(): 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("Alexa.SceneController")) {
|
||||
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;
|
||||
135
src/device/validate.ts
Normal file
135
src/device/validate.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
// 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.
|
||||
import { DISPLAY_CATEGORIES, LIMITS } from "../registry/catalog.js";
|
||||
import { labels, shownAs } from "../registry/resources.js";
|
||||
import { SchemaError } from "../registry/schema.js";
|
||||
import { DeclarationError } from "../registry/types.js";
|
||||
import type { AnyDescriptor, Declared, EndpointView, Label, Semantics } from "../registry/types.js";
|
||||
|
||||
/** An endpoint as discovery sends it, without its capabilities. */
|
||||
export interface EndpointFields {
|
||||
endpointId: string;
|
||||
friendlyName: string;
|
||||
description: string;
|
||||
manufacturerName: string;
|
||||
displayCategories: readonly string[];
|
||||
additionalAttributes: Readonly<Record<string, string>>;
|
||||
cookie?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
// 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: unknown): value is string => typeof value === "string" && value.length > 0;
|
||||
|
||||
/** Throws the first rule of the Endpoint object that the fields break. */
|
||||
export function checkEndpoint(endpoint: EndpointFields): void {
|
||||
const where = { endpointId: isText(endpoint.endpointId) ? endpoint.endpointId : undefined };
|
||||
function refuse(problem: string): never {
|
||||
throw new DeclarationError(where, problem);
|
||||
}
|
||||
const { endpointId, friendlyName, description, manufacturerName, displayCategories, additionalAttributes, cookie } = endpoint;
|
||||
|
||||
if (!isText(endpointId)) refuse("an endpoint needs an endpointId");
|
||||
if (endpointId.length > LIMITS.endpointIdLength || !ENDPOINT_ID.test(endpointId)) {
|
||||
refuse(`the endpointId takes up to ${LIMITS.endpointIdLength} letters, digits, spaces and _ - = # ; : ? @ &`);
|
||||
}
|
||||
if (!isText(friendlyName)) refuse("an endpoint needs a name");
|
||||
if (friendlyName.length > LIMITS.friendlyNameLength || !FRIENDLY_NAME.test(friendlyName)) {
|
||||
refuse(`the name ${JSON.stringify(friendlyName)} takes up to ${LIMITS.friendlyNameLength} letters, digits and spaces, no punctuation`);
|
||||
}
|
||||
if (!isText(manufacturerName) || manufacturerName.length > LIMITS.manufacturerNameLength) {
|
||||
refuse(`the manufacturerName takes 1 to ${LIMITS.manufacturerNameLength} characters`);
|
||||
}
|
||||
if (!isText(description) || description.length > LIMITS.descriptionLength) {
|
||||
refuse(`the description takes 1 to ${LIMITS.descriptionLength} characters`);
|
||||
}
|
||||
|
||||
if (!Array.isArray(displayCategories) || displayCategories.length === 0) refuse("an endpoint needs a display category");
|
||||
const known: readonly string[] = 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 > LIMITS.additionalAttributeLength) {
|
||||
refuse(`${name} takes up to ${LIMITS.additionalAttributeLength} characters`);
|
||||
}
|
||||
}
|
||||
if (cookie !== undefined) {
|
||||
const bytes = Buffer.byteLength(JSON.stringify(cookie) ?? "");
|
||||
if (bytes > LIMITS.cookieBytes) refuse(`the cookie is ${bytes} bytes, ${LIMITS.cookieBytes} is the most`);
|
||||
}
|
||||
}
|
||||
|
||||
/** alexa-discovery.html, "Interface limits". count includes the capabilities the library adds. */
|
||||
export function checkCapabilityCount(endpointId: string, count: number): void {
|
||||
if (count > LIMITS.capabilitiesPerEndpoint) {
|
||||
throw new DeclarationError({ endpointId }, `${count} capabilities, an endpoint takes ${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: Label): string {
|
||||
return name["@type"] === "asset" ? `asset ${name.value.assetId}` : `text ${name.value.locale} ${name.value.text.toLowerCase()}`;
|
||||
}
|
||||
|
||||
function phrases(capability: Declared<unknown>): string[] {
|
||||
const { semantics } = capability.options as { semantics?: Semantics };
|
||||
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.
|
||||
*/
|
||||
export function checkCapability(capability: Declared<unknown>, descriptor: AnyDescriptor, endpoint: EndpointView): void {
|
||||
function refuse(problem: string): never {
|
||||
throw new 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 {
|
||||
labels.parse(friendlyNames, "friendlyNames");
|
||||
} catch (err) {
|
||||
refuse(err instanceof SchemaError && err.path === "friendlyNames" ? "needs a friendly name, from text() or asset()" : (err as Error).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, ${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<string, Declared>();
|
||||
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);
|
||||
}
|
||||
33
src/index.ts
33
src/index.ts
|
|
@ -1,23 +1,34 @@
|
|||
// Relative specifiers carry ".js": Node's ES module loader resolves no extension, and TypeScript maps it back to the .ts.
|
||||
export { default as Alex2MQTT, DEFAULT_HOST } from "./Alex2Node.js";
|
||||
export type { Alex2MQTTOptions } from "./Alex2Node.js";
|
||||
export { default as Device } from "./Device.js";
|
||||
export { AlexaInterface, AlexaInterfaceType } from "./AlexaInterface.js";
|
||||
export type { SupportedMode } from "./AlexaInterface.js";
|
||||
export { ActionMapping, AlexaActions } from "./ActionMapping.js";
|
||||
export { DisplayCategory } from "./DisplayCategory.js";
|
||||
export { AlexaStatusMessage, PowerController, EndpointHealth, TemperatureSensorScale, ThermostatMode } from "./AlexaStatusMessage.js";
|
||||
export type { ChangeCause } from "./AlexaStatusMessage.js";
|
||||
export { AlexaErrorType, AlexaErrorResponse } from "./AlexaErrorResponse.js";
|
||||
export { default as Device } from "./device/Device.js";
|
||||
export type { EndpointDefinition, EndpointJson } from "./device/Device.js";
|
||||
export { Capability } from "./device/Capability.js";
|
||||
export type { CapabilityJson, CommonOptions, Declaration } from "./device/Capability.js";
|
||||
|
||||
// The interface registry and the vocabularies of the Smart Home API
|
||||
// The interfaces, for device.add(), and the registry that holds them by name
|
||||
export { registry, DeclarationError, SchemaError } from "./registry/index.js";
|
||||
export { Alexa, BrightnessController, TemperatureSensor } from "./registry/index.js";
|
||||
export { PowerController, EndpointHealth } from "./compat/enums.js";
|
||||
export { asset, text } from "./registry/resources.js";
|
||||
|
||||
// The vocabularies of the Smart Home API
|
||||
export {
|
||||
ASSETS as Assets, UNITS_OF_MEASURE as Units, ACTIONS as Actions, STATES as States,
|
||||
DISPLAY_CATEGORIES as DisplayCategories,
|
||||
} from "./registry/index.js";
|
||||
export type {
|
||||
ActionId, AssetId, DisplayCategoryName, StateId, UnitOfMeasure,
|
||||
AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor,
|
||||
Label, PropertyDescriptor, Infer, Schema, Temperature, TimeInterval,
|
||||
ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor,
|
||||
InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue,
|
||||
Infer, Schema, Temperature, TimeInterval,
|
||||
} from "./registry/index.js";
|
||||
|
||||
// 1.x
|
||||
export { AlexaInterface } from "./compat/AlexaInterface.js";
|
||||
export type { SupportedMode } from "./compat/AlexaInterface.js";
|
||||
export { ActionMapping } from "./compat/ActionMapping.js";
|
||||
export { AlexaActions, AlexaInterfaceType, DisplayCategory, PowerState } from "./compat/enums.js";
|
||||
export { AlexaStatusMessage, TemperatureSensorScale, ThermostatMode } from "./AlexaStatusMessage.js";
|
||||
export type { ChangeCause } from "./AlexaStatusMessage.js";
|
||||
export { AlexaErrorType, AlexaErrorResponse } from "./AlexaErrorResponse.js";
|
||||
|
|
|
|||
|
|
@ -45,8 +45,8 @@ export const registry = {
|
|||
export { Alexa, BrightnessController, EndpointHealth, PowerController, TemperatureSensor };
|
||||
export { DeclarationError, defineInterface } from "./types.js";
|
||||
export type {
|
||||
AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor, InterfaceDescriptor,
|
||||
Label, PropertyDescriptor,
|
||||
ActionsToDirective, AnyDescriptor, CapabilityExtras, Declared, DirectiveDescriptor, EndpointView, EventDescriptor,
|
||||
InterfaceDescriptor, Label, PropertyDescriptor, Semantics, StatesToRange, StatesToValue,
|
||||
} from "./types.js";
|
||||
export { s, SchemaError } from "./schema.js";
|
||||
export type { Infer, Schema, Temperature, TimeInterval } from "./schema.js";
|
||||
|
|
|
|||
|
|
@ -84,6 +84,21 @@ const TABLE: readonly Row[] = [
|
|||
["Alexa.WakeOnLANController", "1", [], "alexa-wakeonlancontroller.html"],
|
||||
];
|
||||
|
||||
// What 1.5.2 added to the capability object of three of them
|
||||
const EXTRAS: Record<string, AnyDescriptor["discovery"]> = {
|
||||
// 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: string): AnyDescriptor["kind"] {
|
||||
if (namespace.endsWith("Sensor")) return "sensor";
|
||||
if (namespace.endsWith("EventSource")) return "eventSource";
|
||||
|
|
@ -100,6 +115,7 @@ function stub([namespace, version, properties, page]: Row): AnyDescriptor {
|
|||
instanced: false,
|
||||
properties: Object.fromEntries(properties.map((name) => [name, { name, value: s.unknown() }])),
|
||||
directives: {},
|
||||
discovery: EXTRAS[namespace],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
47
src/registry/resources.ts
Normal file
47
src/registry/resources.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// Friendly names: what the user calls an instance, a mode or a preset (resources-and-assets.html).
|
||||
import { ASSETS, RESERVED_WORDS } from "./catalog.js";
|
||||
import type { AssetId } from "./catalog.js";
|
||||
import { at, s, SchemaError } from "./schema.js";
|
||||
import type { Schema } from "./schema.js";
|
||||
import type { Label } from "./types.js";
|
||||
|
||||
/** A friendly name as text, in one locale. */
|
||||
export function text(name: string, locale = "en-US"): Label {
|
||||
return { "@type": "text", value: { text: name, locale } };
|
||||
}
|
||||
|
||||
/** A friendly name from the global Alexa catalog: one id, several names, every language Alexa speaks. */
|
||||
export function asset(assetId: AssetId): Label {
|
||||
return { "@type": "asset", value: { assetId } };
|
||||
}
|
||||
|
||||
const LOCALE = /^[a-z]{2}-[A-Z]{2}$/;
|
||||
const textValue = s.object({
|
||||
text: s.string({ min: 1 }),
|
||||
locale: s.string({ pattern: LOCALE, expects: "a locale like en-US" }),
|
||||
});
|
||||
const assetValue = s.object({ assetId: s.oneOf(ASSETS, "an id of the global Alexa catalog, like Alexa.Setting.Opening") });
|
||||
const typed = s.object({ "@type": s.enum("text", "asset"), value: s.unknown() });
|
||||
const reserved: readonly string[] = RESERVED_WORDS;
|
||||
|
||||
/** One friendly name. An asset has to be in the catalog, a text must not be a word Alexa keeps for itself. */
|
||||
export const label: Schema<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, at(path, "value")) };
|
||||
const named = textValue.parse(value, at(path, "value"));
|
||||
if (reserved.includes(named.text.trim().toLowerCase())) {
|
||||
throw new SchemaError(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. */
|
||||
export const labels = s.array(label, { min: 1 });
|
||||
|
||||
/** What the user is shown for a friendly name: the text, or the id of the asset. */
|
||||
export function shownAs(name: Label): string {
|
||||
return name["@type"] === "text" ? name.value.text : name.value.assetId;
|
||||
}
|
||||
|
|
@ -65,11 +65,13 @@ function shown(input: unknown): string {
|
|||
return text.length > 60 ? `${text.slice(0, 57)}...` : text;
|
||||
}
|
||||
|
||||
function mismatch(path: string, expects: string, input: unknown): SchemaError {
|
||||
/** The error of a value that is not what a schema expects. */
|
||||
export function mismatch(path: string, expects: string, input: unknown): SchemaError {
|
||||
return new SchemaError(path, `expected ${expects}, got ${shown(input)}`);
|
||||
}
|
||||
|
||||
const at = (path: string, key: string): string => (path ? `${path}.${key}` : key);
|
||||
/** The path of a key of the object at path. */
|
||||
export const at = (path: string, key: string): string => (path ? `${path}.${key}` : key);
|
||||
|
||||
function isRecord(input: unknown): input is Record<string, unknown> {
|
||||
return typeof input === "object" && input !== null && !Array.isArray(input);
|
||||
|
|
@ -117,7 +119,12 @@ function literal<V extends string | number | boolean | null>(value: V): Schema<V
|
|||
}
|
||||
|
||||
function enumeration<V extends readonly string[]>(...values: V): EnumSchema<V[number]> {
|
||||
return { ...schema<V[number]>(values.join(" | "), (input) => values.includes(input as string)), 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<V extends string>(values: readonly V[], expects: string): EnumSchema<V> {
|
||||
return { ...schema<V>(expects, (input) => values.includes(input as V)), values };
|
||||
}
|
||||
|
||||
function unknown(): Schema<unknown> {
|
||||
|
|
@ -229,6 +236,7 @@ export const s = {
|
|||
boolean,
|
||||
literal,
|
||||
enum: enumeration,
|
||||
oneOf,
|
||||
unknown,
|
||||
optional,
|
||||
nullable,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,33 @@ export type Label =
|
|||
| { "@type": "text"; value: { text: string; locale: string } }
|
||||
| { "@type": "asset"; value: { assetId: string } };
|
||||
|
||||
/** Phrases ("open", "lower") mapped to one directive (alexa-discovery-objects.html, "ActionMappings object"). */
|
||||
export interface ActionsToDirective {
|
||||
"@type": "ActionsToDirective";
|
||||
actions: string[];
|
||||
directive: { name: string; payload?: Record<string, unknown> };
|
||||
}
|
||||
|
||||
/** States ("open", "closed") mapped to a value of the property (same page, "StateMappings object"). */
|
||||
export interface StatesToValue {
|
||||
"@type": "StatesToValue";
|
||||
states: string[];
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
/** States mapped to a range of values of the property. */
|
||||
export interface StatesToRange {
|
||||
"@type": "StatesToRange";
|
||||
states: string[];
|
||||
range: { minimumValue: number; maximumValue: number };
|
||||
}
|
||||
|
||||
/** The semantics object of a generic controller: at least one of the two lists. */
|
||||
export interface Semantics {
|
||||
actionMappings?: ActionsToDirective[];
|
||||
stateMappings?: Array<StatesToValue | StatesToRange>;
|
||||
}
|
||||
|
||||
export interface PropertyDescriptor<V> {
|
||||
name: string;
|
||||
value: Schema<V>;
|
||||
|
|
@ -48,7 +75,7 @@ export interface CapabilityExtras {
|
|||
}
|
||||
|
||||
/** A capability as declared on an endpoint: what discovery() and validate() of its descriptor are given. */
|
||||
export interface Declared<O = Record<string, unknown>> {
|
||||
export interface Declared<O = unknown> {
|
||||
readonly endpointId: string;
|
||||
readonly namespace: string;
|
||||
/** "" when the interface is declared without an instance. */
|
||||
|
|
@ -67,7 +94,7 @@ export interface EndpointView {
|
|||
readonly friendlyName: string;
|
||||
readonly description: string;
|
||||
readonly displayCategories: readonly string[];
|
||||
/** The other capabilities of the endpoint. */
|
||||
/** The capabilities declared on the endpoint before this one. */
|
||||
readonly capabilities: readonly Declared[];
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue