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