// A contact sensor on a door: Alexa.ContactSensor. It takes no directive. It answers ReportState and sends a // ChangeReport when the door opens or closes. Press Enter to open and close the door. // // ALEX2MQTT_USERNAME=... ALEX2MQTT_PASSWORD=... ALEX2MQTT_ROOT_TOPIC=... node examples/sensor.js // // "alex2node" is the installed package; inside this checkout it resolves to the built dist/. const { Alex2MQTT, ContactSensor } = 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)); // DETECTED is open: the two pieces of the sensor are apart const door = { contact: "NOT_DETECTED", changedAt: new Date() }; const device = bridge.addDevice({ endpointId: "back-door", name: "Back Door", categories: ["CONTACT_SENSOR"] }); // proactivelyReported: Alexa takes ChangeReports for the capability const contact = device.add(ContactSensor, { proactivelyReported: true }); device.state((s) => s.set(contact, "detectionState", door.contact, { timeOfSample: door.changedAt }).health("OK")); async function changed(state) { door.contact = state; door.changedAt = new Date(); // What changed is set here. The rest of device.state(), the health, is the context of the report. const result = await device.changeReport("PHYSICAL_INTERACTION", (s) => s .set(contact, "detectionState", door.contact, { timeOfSample: door.changedAt })); console.log(result.ok ? `the door reported ${state}` : `not reported: ${result.error.message}`); } process.stdin.on("data", () => changed(door.contact === "DETECTED" ? "NOT_DETECTED" : "DETECTED")); bridge.connect();