// A plug, as an ES module: the same library with import. Alexa.PowerController. // // ALEX2MQTT_USERNAME=... ALEX2MQTT_PASSWORD=... ALEX2MQTT_ROOT_TOPIC=... node examples/plug.mjs // // "alex2node" is the installed package; inside this checkout it resolves to the built dist/. import { Alex2MQTT, PowerController } from "alex2node"; const missing = ["ALEX2MQTT_USERNAME", "ALEX2MQTT_PASSWORD", "ALEX2MQTT_ROOT_TOPIC"].filter((name) => !process.env[name]); if (missing.length > 0) { console.error(`${missing.join(", ")} not set. Set the MQTT user name, the password and the root topic of your Alex2MQTT account.`); process.exit(1); } const { ALEX2MQTT_USERNAME, ALEX2MQTT_PASSWORD, ALEX2MQTT_ROOT_TOPIC } = process.env; const bridge = new Alex2MQTT(ALEX2MQTT_USERNAME, ALEX2MQTT_PASSWORD, ALEX2MQTT_ROOT_TOPIC); bridge.on("connect", () => console.log("connected, discover the devices in the Alexa app")); bridge.on("error", (err) => console.error("bridge:", err.message)); const plug = { on: false }; const device = bridge.addDevice({ endpointId: "coffee-plug", name: "Coffee Machine", categories: ["SMARTPLUG"] }); const power = device.add(PowerController); device.state((s) => s.set(power, "powerState", plug.on ? "ON" : "OFF").health("OK")); power.on("TurnOn", (ctx) => { plug.on = true; return ctx.respond(); }); power.on("TurnOff", (ctx) => { plug.on = false; return ctx.respond(); }); bridge.connect();