// A lamp that switches and dims: Alexa.PowerController and Alexa.BrightnessController. // // ALEX2MQTT_USERNAME=... ALEX2MQTT_PASSWORD=... ALEX2MQTT_ROOT_TOPIC=... node examples/lamp.js // // "alex2node" is the installed package; inside this checkout it resolves to the built dist/. const { Alex2MQTT, PowerController, BrightnessController } = require("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)); // The lamp itself. Replace it with what drives yours. const lamp = { on: false, brightness: 100 }; const device = bridge.addDevice({ endpointId: "desk-lamp", name: "Desk Lamp", categories: ["LIGHT"] }); const power = device.add(PowerController); const brightness = device.add(BrightnessController); // The whole state: the answer to ReportState, and the context of every ctx.respond() device.state((s) => s .set(power, "powerState", lamp.on ? "ON" : "OFF") .set(brightness, "brightness", lamp.brightness) .health("OK")); power.on("TurnOn", (ctx) => { lamp.on = true; return ctx.respond(); }); power.on("TurnOff", (ctx) => { lamp.on = false; return ctx.respond(); }); // Both brightness directives turn a lamp on that is off brightness.on("SetBrightness", (ctx) => { lamp.brightness = ctx.payload.brightness; lamp.on = true; return ctx.respond(); }); brightness.on("AdjustBrightness", (ctx) => { lamp.brightness = Math.min(100, Math.max(0, lamp.brightness + ctx.payload.brightnessDelta)); lamp.on = true; return ctx.respond(); }); bridge.connect();