8  Operating from the Cloud: Lambda and Alexa (Explanation)

In this hands-on, send.py wrote desired, but in practice a cloud program such as a Lambda writes it. This chapter explains how the two entry points built in the original project —— Alexa voice control and a web page —— work, and where we stumbled.

flowchart LR
  E["Echo<br>&quot;Turn on the light&quot;"] --> AL["Alexa cloud"]
  AL --> L1["Lambda<br>(Smart Home skill)"]
  W["Web page"] --> L2["Lambda<br>(Function URL)"]
  L1 -- "update desired" --> S[("Device Shadow")]
  L2 -- "update desired" --> S
  S -- "delta" --> D["ESP32"]

Both entry points do the same thing as send.py: “just write desired”. The device side does not care where a command came from.

8.1 Writing the Shadow from Lambda

In Node.js (AWS SDK v3), it looks like this.

const { IoTDataPlaneClient, UpdateThingShadowCommand } = require("@aws-sdk/client-iot-data-plane");
const iot = new IoTDataPlaneClient({ region: "ap-northeast-1" });

async function updateDesired(desired) {
  await iot.send(new UpdateThingShadowCommand({
    thingName: process.env.THING_NAME,
    payload: Buffer.from(JSON.stringify({ state: { desired } })),
  }));
}

// Button: change the value itself every time (Chapter 4)
await updateDesired({ sendSlot: `${slot}-${Date.now()}` });
// Air conditioner: the fields to change + a cmdId (string) that changes every time
await updateDesired({ temp: 26, cmdId: String(Date.now()) });

Give the Lambda’s execution role permissions to read and write only that Thing’s Shadow (iot:UpdateThingShadow, iot:GetThingShadow).

8.2 Alexa Smart Home skill

For appliance control such as “Alexa, turn on X”, use an Alexa Smart Home skill. Alexa sends commands in a fixed format (directives) to the Lambda, which converts them into desired.

Alexa directive Example utterance Conversion to desired
Alexa.Discovery (device discovery) Return the list of controllable devices from the Shadow’s reported
Alexa.PowerController “Turn on the light”, “Turn it off” Button: {sendSlot: "5-<time>"}; air conditioner: {power: true, cmdId}
Alexa.SceneController (running a scene; buttons other than the light) {sendSlot: "<slot>-<time>"}
Alexa.ThermostatController “Set the air conditioner to 26 degrees” {temp: 26, cmdId}
Alexa.ReportState (state shown in the app) Read and return the Shadow’s reported

8.2.1 Where we stumbled

  • The region where the Lambda can live is fixed: the Lambda for a skill targeting Japan (Alexa’s Far East region) must be placed in US West (Oregon, us-west-2). IoT Core can stay in Tokyo; inside the Lambda, specify region: "ap-northeast-1" and write the Shadow across regions
  • Account linking is mandatory: a Smart Home skill requires linking to the user’s account (OAuth 2.0). Instead of writing our own OAuth server, we used an Amazon Cognito user pool
  • The state of a toggle-type light is unknown: whether “turn on” or “turn off”, all we can do is send the same learned signal. If it is operated with the wall switch, the state Alexa believes and the actual state diverge. We declare to Alexa that the light’s power state “cannot be retrieved” (retrievable: false)
  • Alexa’s thermostat modes have no dehumidify or fan-only: the standard modes of ThermostatController are auto, cool, heat, etc.; dehumidify and fan-only cannot be operated by voice (they are operated from the web page)

8.3 Operating from a web page

So that it can be operated from a browser while away from home, we also built a small API using a Lambda function URL (a feature that attaches an HTTPS URL directly to a Lambda).

  • Browser → function URL → Lambda → the Shadow’s desired
  • Every 5 seconds, read the Shadow’s reported and update the state on the screen
WarningDo not add CORS headers in two places

If you configure CORS (allowed origins, etc.) on the function URL, AWS automatically adds CORS headers to the response. If the Lambda code also returns Access-Control-Allow-Origin, there will be two of the same header, and the browser rejects it. Consolidate into one place (the function URL settings).

TipAlways add authentication, even if simple

If you publish the function URL with “no authentication”, anyone who knows the URL can operate your appliances. In the original project, we use a simple scheme in which the Lambda checks a password. More rigorously, use IAM authentication or Cognito.

ImportantSummary of this chapter
  • The cloud side just writes desired. Both Alexa and the web follow the same conversion rules as send.py (values that change every time, cmdId)
  • The Lambda for an Alexa Smart Home skill targeting Japan is in us-west-2. The Shadow can be written across regions
  • Configure function-URL CORS in one place only, and add authentication