API Gateway

API Gateway Overview

The CloudFormation template creates two URIs for our API. One will be for authorized hotel staff to reset the room (“Alexa, Tell smart hotel skill to reset room 211”) which will use the authorizer function. The second will be for hotel guests to set the temperature (“Alexa, Tell smart hotel skill to set room temperature to 72 degrees”) which will not need authorization. Each URI will have a method with a Lambda function that is called.

The first lambda function is for the room reset logic. We called this “smart-hotel-reset-room”. This function will send messages to the IoT Core Topic associated with the specific room, each device within the room is subscribed to it. Examples of this will be turning off the TV, reseting room temperature, turning lights off, and closing the blinds.

Chapter page

Reset Room

Here is the code that backs the /set-room resource. Notice the method request requires authorization using our custom Authorizer function. This is to ensure only authorized hotel employees can reset the room:

import json
import boto3
import datetime
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')
client = boto3.client('iot-data')


def lambda_handler(event, context):
    roomId = event['multiValueQueryStringParameters']['room'][0]
    # TODO implement
    temp = 72
    response = client.publish(
        topic = 'resetRoom',
        qos = 0,
        payload = json.dumps({"roomid": roomId, "timestamp": timestamp, "shades": "up", "theater": "stopped", "thermostat": temp})
    )
    return {
        "statusCode": 200,
    }

Set Temperature

The second Lambda function is for customers to set the temperature. We called it ‘smart-hotel-set-temp’ and the code simply writes to the temperature topic for the specific room. The thermostat is subscribed to this topic. The roomId and temperature is passed in from the API gateway request.

import json
import boto3
import datetime
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')
client = boto3.client('iot-data')


def lambda_handler(event, context):
    temp = event['multiValueQueryStringParameters']['temp'][0]
    print(event)
    roomId = 101
    response = client.publish(
        topic = 'setTemp',
        qos = 0,
        payload = json.dumps({"roomid": roomId,"timestamp": timestamp, "thermostat": temp })
    )
    return {
        "statusCode": 200,
    } 

We will not be authorizing calls to this URI since the customers will not need an account to change their temperature.