Alex2Node/examples/legacy/ExamplePowerControllerWithMomentary.js
David 8379a65d78 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>
2026-09-28 21:38:07 +00:00

111 lines
3.7 KiB
JavaScript

// 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();
});