examples: one runnable file per recipe on the 2.0 API, the 1.x files in examples/legacy

Ten recipes: lamp, colour lamp, thermostat, blind, lock (deferred), contact
sensor (ChangeReport), scene, doorbell (raise), typed errors, and a plug as an
ES module. Each reads ALEX2MQTT_USERNAME, _PASSWORD and _ROOT_TOPIC and names
the ones that are missing. The nine examples of 1.5.2 move to examples/legacy
unchanged.

test/examples.test.js starts every file with node, its broker connection sent
to a broker on 127.0.0.1 (test/helpers/loopback.js), discovers the device,
sends directives and checks the answers. A legacy file is started and its
discovery compared with the answer the 1.5.2 build gave, recorded in
test/fixtures/legacy-examples.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
David 2026-09-28 21:38:07 +00:00
parent 2cbcde563e
commit 8379a65d78
25 changed files with 1705 additions and 0 deletions

View file

@ -0,0 +1,111 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
ActionMapping,
AlexaActions,
PowerController,
EndpointHealth
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Simulated in-memory device state (used for example/demo purposes)
let outputState = PowerController.OFF;
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name
const deviceName = "Bedroom Blinds";
// Register the device with a unique endpoint ID
const blinds = alex2NodeClient.registerDevice(deviceName, "bedroom-blinds-1");
// Add basic Alexa capabilities to the device
blinds.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
// Add a toggle controller capability for custom on/off-style commands
const toggle = blinds.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER);
// Toggle controllers require an instance name to differentiate from other controllers
toggle.setInstance("NodeJS.Toggle");
// Optionally, add a friendly name to improve how Alexa refers to this capability
toggle.addFriendlyName(deviceName, "en-US");
// Define how Alexa's "Open" and "Close" actions map to "TurnOff" and "TurnOn" commands
// This allows controlling blinds via both open/close and on/off style requests
const closeMapping = new ActionMapping([AlexaActions.Close], "TurnOn");
const openMapping = new ActionMapping([AlexaActions.Open], "TurnOff");
// Action mappings are only supported by generic controller interfaces.
// More details:
// https://developer.amazon.com/en-US/docs/alexa/device-apis/alexa-discovery-objects.html#action-mapping
// https://developer.amazon.com/en-US/docs/alexa/device-apis/generic-controllers.html
toggle.addActionMapping(closeMapping);
toggle.addActionMapping(openMapping);
// Log the device name to verify registration
console.log(blinds.getName());
/**
* Handle Alexa's ReportState directive.
* This occurs when Alexa queries the current state of the device (e.g., during routines or device status checks).
*/
blinds.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const status = blinds.getStatusMessage(correlationToken);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy
.addPowerControllerProp(outputState) // Report power state
.addToggleControllerProp(outputState, "NodeJS.Toggle"); // Report toggle controller state
status.send(); // Send the state report back to Alexa
});
/**
* Handle incoming control directives (e.g., TurnOn, TurnOff).
* These directives come from Alexa when a user issues a command.
*/
blinds.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
if (
interfaceType === AlexaInterfaceType.TOGGLE_CONTROLLER ||
interfaceType === AlexaInterfaceType.POWER_CONTROLLER
) {
const name = directive.header.name;
const token = directive.header.correlationToken;
// Update the internal state based on the command
if (name === "TurnOn") {
outputState = PowerController.ON;
console.log("Turning ON");
} else if (name === "TurnOff") {
outputState = PowerController.OFF;
console.log("Turning OFF");
}
// Respond to the directive with the updated device status
const status = blinds.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK)
.addToggleControllerProp(outputState, "NodeJS.Toggle")
.addPowerControllerProp(outputState)
.send();
}
});

View file

@ -0,0 +1,120 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
DisplayCategory,
EndpointHealth,
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Simulated in-memory device state (used for example/demo purposes)
let currentMode = "mode.fanmode.Normal";
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name (Test mode controller)
const deviceName = "Test mode controller";
// Register the device with a unique endpoint ID (unique per root topic, e.g. "fan-1")
const modeControllerDevice = alex2NodeClient.registerDevice(
deviceName,
"fan-1",
[DisplayCategory.OTHER]
);
// Add the 'MODE_CONTROLLER' capability for controlling device modes
const modeController = modeControllerDevice.addCapability(
AlexaInterfaceType.MODE_CONTROLLER
);
modeController.setInstance("mode.fanmode");
modeController.addFriendlyName("Fan Mode", "en-US");
modeController.addSupportedModes([
{
value: "mode.fanmode.Normal",
modeResources: {
friendlyNames: [
{
"@type": "text",
value: {
text: "Normal",
locale: "en-US",
},
},
],
},
},
{
value: "mode.fanmode.Low",
modeResources: {
friendlyNames: [
{
"@type": "text",
value: {
text: "Low",
locale: "en-US",
},
},
],
},
},
]);
// Log the device name to verify registration
console.log(modeControllerDevice.getName());
/**
* Handle Alexa's ReportState directive.
* This occurs when Alexa queries the current state of the device (e.g., during routines or device status checks).
*/
modeControllerDevice.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const status = modeControllerDevice.getStatusMessage(correlationToken);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy
.addModeControllerProp("mode.fanmode", currentMode);
status.send(); // Send the state report back to Alexa
});
/**
* Handle incoming control directives (e.g., SetMode).
* These directives come from Alexa when a user issues a command.
*/
modeControllerDevice.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
// Ensure the interfaceType is either PowerController or other valid interfaces
if (interfaceType === AlexaInterfaceType.MODE_CONTROLLER) {
const name = directive.header.name;
const token = directive.header.correlationToken;
const instance = directive.header.instance;
if (instance == "mode.fanmode") {
if (name === "SetMode") {
currentMode = directive.payload.mode;
}
}
const status = modeControllerDevice.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy
.addModeControllerProp("mode.fanmode", currentMode);
status.send(); // Send the state report back to Alexa
}
});

View file

@ -0,0 +1,82 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
EndpointHealth
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Simulated in-memory device state (used for example/demo purposes)
let outputState = PowerController.OFF; // Initialize the power state to OFF
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name (bedroom light)
const deviceName = "Bedroom Light";
// Register the device with a unique endpoint ID (unique per root topic, e.g. "bedroom-light-1")
const bedroomLight = alex2NodeClient.registerDevice(deviceName, "bedroom-light-1");
// Add the PowerController capability (for turning on/off the device)
bedroomLight.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
// Log the device name to verify registration
console.log(bedroomLight.getName());
/**
* Handle Alexa's ReportState directive.
* This occurs when Alexa queries the current state of the device (e.g., during routines or device status checks).
*/
bedroomLight.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const status = bedroomLight.getStatusMessage(correlationToken);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy
.addPowerControllerProp(outputState); // Report the current power state (ON/OFF)
status.send(); // Send the state report back to Alexa
});
/**
* Handle incoming control directives (e.g., TurnOn, TurnOff).
* These directives come from Alexa when a user issues a command.
*/
bedroomLight.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
// Ensure the interfaceType is either PowerController or other valid interfaces
if (interfaceType === AlexaInterfaceType.POWER_CONTROLLER) {
const name = directive.header.name;
const token = directive.header.correlationToken;
// Update the internal state based on the command (TurnOn / TurnOff)
if (name === "TurnOn") {
outputState = PowerController.ON;
console.log("Turning ON the Bedroom Light");
} else if (name === "TurnOff") {
outputState = PowerController.OFF;
console.log("Turning OFF the Bedroom Light");
}
// Respond to the directive with the updated device status
const status = bedroomLight.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK)
.addPowerControllerProp(outputState)
.send();
}
});

View file

@ -0,0 +1,92 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
EndpointHealth
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Simulated in-memory device state (used for example/demo purposes)
let outputState = PowerController.OFF; // Initialize the power state to OFF
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name (deferred light)
const deviceName = "Deferred Light";
// Register the device with a unique endpoint ID (unique per root topic, e.g. "deferred-light-1")
const deferredLight = alex2NodeClient.registerDevice(deviceName, "deferred-light-1");
// Add the PowerController capability (for turning on/off the device)
deferredLight.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
// Log the device name to verify registration
console.log(deferredLight.getName());
/**
* Handle Alexa's ReportState directive.
* This occurs when Alexa queries the current state of the device (e.g., during routines or device status checks).
*/
deferredLight.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
// Step 1: Send a DeferredResponse after ~2 seconds
setTimeout(() => {
const deferred = deferredLight.getStatusMessage(correlationToken, false, true); // isDeferred = true
deferred.addEstimatedDeferralTime(20).send();
console.log("Sent DeferredResponse");
}, 2000); // simulate slight delay before deferred response
// Step 2: Send actual StateReport after 10 seconds
setTimeout(() => {
const status = deferredLight.getStatusMessage(correlationToken,false,false); // normal StateReport
status
.addHealthProp(EndpointHealth.OK)
.addPowerControllerProp(outputState)
.send(true);
console.log("Sent actual StateReport with device status");
}, 8000);
});
/**
* Handle incoming control directives (e.g., TurnOn, TurnOff).
* These directives come from Alexa when a user issues a command.
*/
deferredLight.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
// Ensure the interfaceType is either PowerController or other valid interfaces
if (interfaceType === AlexaInterfaceType.POWER_CONTROLLER) {
const name = directive.header.name;
const token = directive.header.correlationToken;
// Update the internal state based on the command (TurnOn / TurnOff)
if (name === "TurnOn") {
outputState = PowerController.ON;
console.log("Turning ON the Deferred Light");
} else if (name === "TurnOff") {
outputState = PowerController.OFF;
console.log("Turning OFF the Deferred Light");
}
// Respond to the directive with the updated device status
const status = deferredLight.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK)
.addPowerControllerProp(outputState)
.send();
}
});

View file

@ -0,0 +1,99 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
EndpointHealth
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Simulated in-memory device state (used for example/demo purposes)
let outputState = PowerController.OFF; // Initialize the power state to OFF
let brightness = 100; // 0-100, what Alexa.BrightnessController reports
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name (dimmable living room light)
const deviceName = "Living Room Light";
// Register the device with a unique endpoint ID (unique per root topic, e.g. "living-room-light-1")
const livingRoomLight = alex2NodeClient.registerDevice(deviceName, "living-room-light-1");
// Declare every capability the device reports: on/off AND brightness (a property Alexa has not been told about is ignored)
livingRoomLight.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
livingRoomLight.addCapability(AlexaInterfaceType.BRIGHTNESS_CONTROLLER);
// Log the device name to verify registration
console.log(livingRoomLight.getName());
// Clamp a brightness to Alexa's 0-100 range
const clamp = (value) => Math.max(0, Math.min(100, Math.round(value)));
/**
* Handle Alexa's ReportState directive.
* This occurs when Alexa queries the current state of the device (e.g., during routines or device status checks).
*/
livingRoomLight.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const status = livingRoomLight.getStatusMessage(correlationToken);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy
.addPowerControllerProp(outputState) // Report the current power state (ON/OFF)
.addBrightnessControllerProp(brightness); // Report the current brightness (0-100)
status.send(); // Send the state report back to Alexa
});
/**
* Handle incoming control directives (TurnOn / TurnOff, SetBrightness / AdjustBrightness).
* These directives come from Alexa when a user issues a command.
*/
livingRoomLight.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
const name = directive.header.name;
const token = directive.header.correlationToken;
if (interfaceType === AlexaInterfaceType.POWER_CONTROLLER) {
// Update the internal state based on the command (TurnOn / TurnOff)
if (name === "TurnOn") {
outputState = PowerController.ON;
console.log("Turning ON the Living Room Light");
} else if (name === "TurnOff") {
outputState = PowerController.OFF;
console.log("Turning OFF the Living Room Light");
}
} else if (interfaceType === AlexaInterfaceType.BRIGHTNESS_CONTROLLER) {
// "Set the light to 40 percent" -> SetBrightness { brightness }; "dim the light" -> AdjustBrightness { brightnessDelta }
if (name === "SetBrightness") {
brightness = clamp(directive.payload.brightness);
} else if (name === "AdjustBrightness") {
brightness = clamp(brightness + directive.payload.brightnessDelta);
}
outputState = brightness > 0 ? PowerController.ON : PowerController.OFF; // a dimmer at 0 is off
console.log(`Living Room Light brightness is now ${brightness}%`);
} else {
return; // not one of ours
}
// Respond to the directive with the full device status (both properties, whichever one changed)
const status = livingRoomLight.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK)
.addPowerControllerProp(outputState)
.addBrightnessControllerProp(brightness)
.send();
});

View file

@ -0,0 +1,95 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
AlexaErrorType,
EndpointHealth,
} = require("alex2node");
require("dotenv").config();
let outputState = PowerController.OFF;
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect();
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
const errorLight = alex2NodeClient.registerDevice("bad light", "bad-light-1");
errorLight.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
console.log(errorLight.getName());
// Error cycling setup
const errorCycle = [
AlexaErrorType.ENDPOINT_LOW_POWER,
AlexaErrorType.VALUE_OUT_OF_RANGE,
AlexaErrorType.HARDWARE_MALFUNCTION,
AlexaErrorType.BRIDGE_UNREACHABLE,
AlexaErrorType.FIRMWARE_OUT_OF_DATE,
AlexaErrorType.NOT_CALIBRATED,
AlexaErrorType.RATE_LIMIT_EXCEEDED,
];
let currentErrorIndex = 0;
/**
* Always return HARDWARE_MALFUNCTION error on state queries.
*/
errorLight.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const errorResponse = errorLight.getErrorMessage(correlationToken);
errorResponse.setErrorMessage(
AlexaErrorType.HARDWARE_MALFUNCTION,
"The device is currently busy and cannot report its state."
);
console.log("Sending error: HARDWARE_MALFUNCTION");
errorResponse.send();
});
/**
* Handle control directives with 90% error chance, cycling through fixed errors.
*/
errorLight.on("Event", (directive, interfaceType) => {
if (interfaceType === AlexaInterfaceType.POWER_CONTROLLER) {
const name = directive.header.name;
const token = directive.header.correlationToken;
const shouldError = Math.random() < 0.9;
if (shouldError) {
const errorType = errorCycle[currentErrorIndex];
currentErrorIndex = (currentErrorIndex + 1) % errorCycle.length;
const errorResponse = errorLight.getErrorMessage(token);
errorResponse.setErrorMessage(
errorType,
`Failed to process ${name} due to ${errorType.replace(/_/g, " ").toLowerCase()}.`
);
console.log(`Sending error: ${errorType}`);
errorResponse.send();
return;
}
// Success path
if (name === "TurnOn") {
outputState = PowerController.ON;
console.log("Turning ON the Light");
} else if (name === "TurnOff") {
outputState = PowerController.OFF;
console.log("Turning OFF the Light");
}
const status = errorLight.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK)
.addPowerControllerProp(outputState)
.send();
}
});

View file

@ -0,0 +1,111 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
DisplayCategory,
EndpointHealth
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Simulated in-memory device state
let outputState = PowerController.OFF;
const momentaryModeInstance = "mode.signal.beep";
const defaultMomentaryMode = "mode.signal.beep.Normal";
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name and register it
const deviceName = "Kitchen Light";
const kitchenLight = alex2NodeClient.registerDevice(
deviceName,
"kitchen-light-1",
[DisplayCategory.LIGHT]
);
// Add PowerController capability
kitchenLight.addCapability(AlexaInterfaceType.POWER_CONTROLLER);
// Add ModeController for momentary "beep" functionality
const momentaryController = kitchenLight.addCapability(AlexaInterfaceType.MODE_CONTROLLER);
momentaryController.setInstance(momentaryModeInstance);
momentaryController.addFriendlyName("Signal", "en-US");
momentaryController.addSupportedModes([
{
value: "mode.signal.beep.Normal",
modeResources: {
friendlyNames: [{
"@type": "text",
value: { text: "Normal", locale: "en-US" }
}]
}
},
{
value: "mode.signal.beep.Beep",
modeResources: {
friendlyNames: [{
"@type": "text",
value: { text: "Beep", locale: "en-US" }
}]
}
}
]);
// Log the device name to verify registration
console.log(kitchenLight.getName());
/**
* Handle Alexa's ReportState directive
*/
kitchenLight.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const status = kitchenLight.getStatusMessage(correlationToken);
status
.addHealthProp(EndpointHealth.OK)
.addPowerControllerProp(outputState)
.addModeControllerProp(momentaryModeInstance, defaultMomentaryMode);
status.send();
});
/**
* Handle incoming directives (PowerController and ModeController)
*/
kitchenLight.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
const { name, correlationToken, instance } = directive.header;
const status = kitchenLight.getStatusMessage(correlationToken, true).addHealthProp(EndpointHealth.OK);
// PowerController logic
if (interfaceType === AlexaInterfaceType.POWER_CONTROLLER) {
if (name === "TurnOn") {
outputState = PowerController.ON;
console.log("Turning ON the Kitchen Light");
} else if (name === "TurnOff") {
outputState = PowerController.OFF;
console.log("Turning OFF the Kitchen Light");
}
status.addPowerControllerProp(outputState);
}
// Momentary ModeController logic
else if (interfaceType === AlexaInterfaceType.MODE_CONTROLLER && instance === momentaryModeInstance) {
if (name === "SetMode") {
const modeValue = directive.payload.mode;
console.log(`[Momentary Trigger] Received mode: ${modeValue}`);
}
status.addModeControllerProp(momentaryModeInstance, defaultMomentaryMode);
}
status.send();
});

View file

@ -0,0 +1,204 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
TemperatureSensorScale,
DisplayCategory,
ThermostatMode,
EndpointHealth,
} = require("alex2node");
require("dotenv").config(); // Load environment variables from .env file
// Load MQTT connection credentials and root topic from environment variables
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
// Create and initialize a new Alexa-to-MQTT client
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false);
alex2NodeClient.connect(); // Connect to the MQTT broker
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
// Define the device name (Thermostat Test)
const deviceName = "Thermostat Test";
// Register the thermostat device with a unique endpoint ID
const thermostat = alex2NodeClient.registerDevice(
deviceName,
"thermostat-1",
[DisplayCategory.TEMPERATURE_SENSOR, DisplayCategory.THERMOSTAT,DisplayCategory.OTHER]
);
// Add thermostat-related capabilities
thermostat.addCapability(AlexaInterfaceType.THERMOSTAT_CONTROLLER); // Allows Alexa to control thermostat modes and setpoints
thermostat.addCapability(AlexaInterfaceType.TEMPERATURE_SENSOR); // Allows Alexa to read current temperature from the sensor
const modeController = thermostat.addCapability(
AlexaInterfaceType.MODE_CONTROLLER
);
modeController.setInstance("mode.fanmode");
modeController.addFriendlyName("Fan", "en-US");
modeController.addSupportedModes([
{
value: "mode.fanmode.Auto",
modeResources: {
friendlyNames: [
{
"@type": "text",
value: {
text: "Auto",
locale: "en-US",
},
},
],
},
},
{
value: "mode.fanmode.On",
modeResources: {
friendlyNames: [
{
"@type": "text",
value: {
text: "On",
locale: "en-US",
},
},
],
},
},
]);
// Log the device name to verify registration
console.log(thermostat.getName());
/**
* Handle Alexa's ReportState directive.
* This occurs when Alexa queries the current state of the thermostat (e.g., during routines or device status checks).
*/
const deviceData = { // all temperatures in Fahrenheit; the library converts to Celsius for Alexa
lowerSetpoint: 50,
upperSetpoint: 70,
targetSetpoint: 60,
current: 69,
thermostatMode: ThermostatMode.HEAT,
fanMode:"mode.fanmode.Auto"
};
thermostat.on("ReportState", (payload) => {
// console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
let status = thermostat.getStatusMessage(correlationToken);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy and reachable
.addModeControllerProp("mode.fanmode", deviceData.fanMode)
.addTemperatureSensorProp(
TemperatureSensorScale.FAHRENHEIT,
deviceData.current
) // Report current temperature
.addThermostatModeProp(deviceData.thermostatMode); // Report current thermostat mode
if (deviceData.thermostatMode == "AUTO") {
status = status
.addThermostatControllerProp(
"lowerSetpoint",
TemperatureSensorScale.FAHRENHEIT,
deviceData.lowerSetpoint
) // Lower bound of temperature range
.addThermostatControllerProp(
"upperSetpoint",
TemperatureSensorScale.FAHRENHEIT,
deviceData.upperSetpoint
); // Upper bound of temperature range
} else {
status = status.addThermostatControllerProp(
"targetSetpoint",
TemperatureSensorScale.FAHRENHEIT,
deviceData.targetSetpoint
); // Single setpoint (HEAT / COOL)
}
status.send(); // Send the full state report back to Alexa
});
/**
* Handle incoming control directives for the thermostat.
* These directives come from Alexa when a user issues a command (e.g., to change temperature or mode).
*/
thermostat.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
if (interfaceType === AlexaInterfaceType.THERMOSTAT_CONTROLLER) {
const name = directive.header.name;
const token = directive.header.correlationToken;
if (name == "SetTargetTemperature") {
console.log({ name: directive.payload });
if (directive.payload.upperSetpoint) {
deviceData.upperSetpoint = parseTempValue(
directive.payload.upperSetpoint
);
}
if (directive.payload.lowerSetpoint) {
deviceData.lowerSetpoint = parseTempValue(
directive.payload.lowerSetpoint
);
}
if (directive.payload.targetSetpoint) {
deviceData.targetSetpoint = parseTempValue(
directive.payload.targetSetpoint
);
}
}
if (name == "SetThermostatMode") {
console.log(directive.payload.thermostatMode);
if (directive.payload.thermostatMode) {
deviceData.thermostatMode = directive.payload.thermostatMode.value;
}
}
let status = thermostat.getStatusMessage(token, true);
status
.addHealthProp(EndpointHealth.OK) // Device is healthy and reachable
.addModeControllerProp("mode.fanmode", deviceData.fanMode)
.addTemperatureSensorProp(
TemperatureSensorScale.FAHRENHEIT,
deviceData.current
) // Report current temperature
.addThermostatModeProp(deviceData.thermostatMode); // Report current thermostat mode
if (deviceData.thermostatMode == "AUTO") {
status = status
.addThermostatControllerProp(
"lowerSetpoint",
TemperatureSensorScale.FAHRENHEIT,
deviceData.lowerSetpoint
) // Lower bound of temperature range
.addThermostatControllerProp(
"upperSetpoint",
TemperatureSensorScale.FAHRENHEIT,
deviceData.upperSetpoint
); // Upper bound of temperature range
} else {
status = status.addThermostatControllerProp(
"targetSetpoint",
TemperatureSensorScale.FAHRENHEIT,
deviceData.targetSetpoint
); // Single setpoint (HEAT / COOL)
}
status.send(); // Send the full state report back to Alexa
}
});
function parseTempValue(data) {
console.log(data);
if (data.scale === "FAHRENHEIT") {
return data.value;
}
const fahrenheit = (data.value * 9) / 5 + 32;
return fahrenheit;
}

View file

@ -0,0 +1,80 @@
// Import the library ("alex2node" is the installed package; inside this checkout it resolves to the built dist/ via package.json "exports")
const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
EndpointHealth,
} = require("alex2node");
require("dotenv").config();
const username = process.env.MQTT_USERNAME;
const password = process.env.MQTT_PASSWORD;
const rootTopic = process.env.MQTT_ROOT_TOPIC;
const alex2NodeClient = new Alex2MQTT(username, password, rootTopic, false); // set the 4th argument to true to print every MQTT payload
alex2NodeClient.connect();
alex2NodeClient.on("error", (e) => console.error("broker:", e.message)); // Log broker errors (on 1.5.0 this listener is also what keeps an outage from killing the process)
const deviceName = "Custom Device";
const customToggle = alex2NodeClient.registerDevice(deviceName, "custom-device-1");
// Define 8 toggle instances and friendly names
const switchCount = 8;
const instanceNames = Array.from({ length: switchCount }, (_, i) => `nodejs.toggle.switch${i + 1}`);
const friendlyNames = Array.from({ length: switchCount }, (_, i) => `Switch ${i + 1}`);
// Add toggle capabilities and store toggle objects
const toggles = [];
for (let i = 0; i < switchCount; i++) {
const toggle = customToggle.addCapability(AlexaInterfaceType.TOGGLE_CONTROLLER);
toggle.setInstance(instanceNames[i]);
toggle.addFriendlyName(friendlyNames[i], "en-US");
toggles.push(toggle);
}
// Output states for all switches
const toggleStates = Array(switchCount).fill(PowerController.OFF);
console.log(customToggle.getName());
customToggle.on("ReportState", (payload) => {
console.log("ReportState received!", payload);
const { correlationToken } = payload.header;
const status = customToggle.getStatusMessage(correlationToken);
status.addHealthProp(EndpointHealth.OK);
// Report all toggle states
for (let i = 0; i < switchCount; i++) {
status.addToggleControllerProp(toggleStates[i], instanceNames[i]);
}
status.send();
});
customToggle.on("Event", (directive, interfaceType) => {
console.log("Event received", { directive, interfaceType });
if (interfaceType === AlexaInterfaceType.TOGGLE_CONTROLLER) {
const { name, correlationToken, instance } = directive.header;
const index = instanceNames.indexOf(instance);
if (index !== -1) {
if (name === "TurnOn") {
toggleStates[index] = PowerController.ON;
console.log(`Turning ON ${friendlyNames[index]}`);
} else if (name === "TurnOff") {
toggleStates[index] = PowerController.OFF;
console.log(`Turning OFF ${friendlyNames[index]}`);
}
const status = customToggle.getStatusMessage(correlationToken, true);
status
.addHealthProp(EndpointHealth.OK)
.addToggleControllerProp(toggleStates[index], instance)
.send();
}
}
});

12
examples/legacy/README.md Normal file
View file

@ -0,0 +1,12 @@
# Examples of 1.5.2
The nine examples of alex2node 1.5.2, as they were. They run on 2.0 through its compat layer, which keeps the 1.x
API: `registerDevice()`, `addCapability()`, the `Event` and `ReportState` listeners, `getStatusMessage()` and
`getErrorMessage()`. `test/examples.test.js` starts each of them and compares its discovery answer with the one
1.5.2 gave; 2.0 adds the `Alexa` interface at the end of the capabilities and changes nothing else in them.
They read `MQTT_USERNAME`, `MQTT_PASSWORD` and `MQTT_ROOT_TOPIC` from the environment or from a `.env` file, with
`dotenv`, which is a development dependency of this repository.
For a new program use the examples one directory up. [docs/wire-changes.md](../../docs/wire-changes.md) lists what
a 1.x program can observe of 2.0.