Alex2Node/examples/README.md
David 8379a65d78 examples: one runnable file per recipe on the 2.0 API, the 1.x files in examples/legacy
Ten recipes: lamp, colour lamp, thermostat, blind, lock (deferred), contact
sensor (ChangeReport), scene, doorbell (raise), typed errors, and a plug as an
ES module. Each reads ALEX2MQTT_USERNAME, _PASSWORD and _ROOT_TOPIC and names
the ones that are missing. The nine examples of 1.5.2 move to examples/legacy
unchanged.

test/examples.test.js starts every file with node, its broker connection sent
to a broker on 127.0.0.1 (test/helpers/loopback.js), discovers the device,
sends directives and checks the answers. A legacy file is started and its
discovery compared with the answer the 1.5.2 build gave, recorded in
test/fixtures/legacy-examples.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-28 21:38:07 +00:00

2.3 KiB

Examples

One file per recipe, on the 2.0 API. Each file is complete: it declares one device, answers its directives and connects. The state of the device is an object in the file, which you replace with what drives your device.

File Device Interfaces Shows
lamp.js lamp PowerController, BrightnessController handlers, device.state(), ctx.respond()
color-lamp.js colour lamp + ColorController, ColorTemperatureController a state that depends on the mode of the device
thermostat.js thermostat ThermostatController, TemperatureSensor one setpoint, three modes, temperature scales
blind.js roller blind RangeController an instance, friendly names, semantics for open and close
lock.js lock LockController ctx.defer() for an answer that takes longer than 7 seconds
sensor.js contact sensor ContactSensor device.changeReport()
scene.js scene SceneController ActivationStarted and DeactivationStarted
doorbell.js doorbell DoorbellEventSource device.raise()
errors.js fan PowerController, RangeController AlexaErrors, ctx.error()
plug.mjs plug PowerController the library as an ES module

Run one

The examples read the MQTT user name, the password and the root topic of your Alex2MQTT account from the environment, and say which variable is missing:

ALEX2MQTT_USERNAME=... ALEX2MQTT_PASSWORD=... ALEX2MQTT_ROOT_TOPIC=... node examples/lamp.js

In a checkout of this repository npm install comes first: it builds dist/, which require("alex2node") resolves to. Then discover the devices in the Alexa app.

sensor.js and doorbell.js wait for the Enter key: it opens and closes the door, and rings the bell. lock.js takes BOLT_SECONDS, the time its bolt needs, 8 by default.

What was tested

test/examples.test.js starts every file with node, against a broker on 127.0.0.1, discovers the device, sends it directives and checks the answers. The examples were not run against an Alexa account. doorbell.js publishes to <root>/event, and whether a press reaches Alexa depends on the Alex2MQTT service relaying that topic.

1.x

legacy/ has the nine examples of 1.5.2, on the 1.x API.