Alex2Node/examples/ExampleToggleController.js

77 lines
No EOL
2.5 KiB
JavaScript

const {
Alex2MQTT,
AlexaInterfaceType,
PowerController,
} = require("../dist/index.js");
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, true);
alex2NodeClient.connect();
const deviceName = "Custom Device";
const customToggle = alex2NodeClient.registerDevice(deviceName, "endpoint8");
// 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("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("OK")
.addToggleControllerProp(toggleStates[index], instance)
.send();
}
}
});