Implement a Serverless Event Handler for Raspberry PI Telemetry on AWS IoT Core

Ezequiel Miranda
Devjam
Published in
6 min readDec 20, 2021

This article is part of a series. Check out the series: Part 1 and Part 2, Part 3

Introduction

In a previous article, we used the AWS Lambda service to host a Node JS lambda function with the goal of using it as an event handler on an AWS IoT Core instance.

This Node JS function receives data from the AWS IoT Core (MQTT) broker and stores it in a DynamoDB collection.

This time, we will improve the stack by using The Serverless Framework. A complete automation tool that helps you build, test, deploy and scale your serverless stack rapidly without worrying about infrastructure.

This is how our stack will look after adding the Serverless Framework:

We will guide you through the steps to using the Serverless Framework to deploy Node JS Lambda functions as Serverless services.

But before we go deep into the details of implementation, let’s refresh some concepts related to serverless computing.

Function as a service in cloud computing

This computing concept emerged not too long too, It was first introduced by Amazon in 2014 with their Lambda product. The most exciting aspect of using cloud functions is that you don’t have to worry about managing servers during the development process. This approach to thought, design, and building applications place developers focus on logic and removes their worries from the servers.

The FaaS(Function as service Model) model has some similarities with the PaaS(platform as a service) mode but with the difference that FaaS depends on an event-driven architecture.

Another very cool feature of the FaaS model is auto-scaling; this mechanism can automatically detect an increased demand for computation and then the server resources are scaled.

Some features of this model:
- Focus on the logic
- Event-driven architecture
- Auto-scaling
- Pay-as-you-go model (Paying only for the computing time you use)
- Removal of the need for developers to manage servers

Uses
- Data processing
- Stream Processing
- Extract-transform-load(ETL)
- Creating API and micro-services
- Internet of things (IoT) services for internet-connected devices
- Saving data to a database
- Processing files
- Performing scheduled tasks

Serverless Framework

http://www.serverless.com

The Serverless framework comes with a command-line toolkit that helps you build, test, deploy and scale your serverless tack rapidly without worrying about infrastructure. It works, with different infrastructure service providers, such as AWS, Azure, Google Cloud Platform.

These are the steps we are going to accomplish in this article:
1. Install The Serverless Framework
2. Set up the AWS credentials
3. Initiate applications and create service
4. Migrate AWS lambda function to the Serverless framework
5. Invoke service locally
6. Deploy function
7. Invoke remote function

Install the Serverless Framework

Installing The Serverless Framework via NPM is easy. By running the following command you will get the Serverless NPM package installed globally in your environment.

npm install -g serverless

If everything goes fine, you will have access to the Serverless CLI application on your console with the command serverless or sls

You can run the following command and check the Serverless version installed on your computer.

serverless -version

Output

Framework Core: 2.64.1
Plugin: 5.5.0
SDK: 4.3.0
Components: 3.17.1

Set up AWS credentials

When using the AWS provider, the most important thing to know is that you’ll need to set up your credentials to create and deploy functions on AWS more easily.

TO achieve this, you must create an AWS account and then create an IAM User and Access Key.

The Serverless documentation gives us step-by-step instructions o how to generate these credentials.

Here is the direct link:

https://www.serverless.com/framework/docs/providers/aws/guide/credentials#create-an-iam-user-and-access-key

Now that you’ve generated these credentials, you can set them up in your local environment.

AWS Credentials you need

**IAM User:** serverless-adm**Access key ID:** #ACCESS_KEY**Secret accesskey**: #SECRET_ACCESS_KEY

Set up AWS profile with Serverless

Serverless provides a convenient way to configure AWS profiles with the help of the Serverless config credentials command.

serverless config credentials — provider aws — key ACCESS_KEY — secret SECRET_ACCESS_KEY

Initiate applications and create service

After you have completed your Serverless framework setup, it’s time to start coding. In this part, you’ll create and deploy a simple Node JS service

Create service (Lambda function)

To create the service, we use the interactive console applications provided by The Serverless Framework in the console, tun the command serverless


>> serverless
What do you want to make? AWS — Node.js — Starter
What do you want to call this project? iot-save-telemetry-data
Downloading “aws-node” template…Project successfully created in iot-save-telemetry-data folderWhat org do you want to add this service to? the-service-name
What application do you want to add this to? iot-core-services
Your project has been setup with org ezequielmiranda87 and app iot-core-services

Now that you have created a boilerplate project with the basic set-up, let’s take a look at the folder structure:


iot-save-telemetry-data/
— README.md
— handler.js
— serverless.yml

First, you can find the commonly used README.md file with some information and instructions regarding the service created by The Serverless framework.

In the handler.js file, you can find. the Node JS function. This is how the boilerplate functions look:

serverless.yml is where you define The Serverless stack, functions, events, and resources for your service. It looks like this:

Update the hanlder with the event handler:

From our previous lambda function code, we adapt it for use with The Serverless framework.

The code shown below, will receive data from our IoT device, routed by the AWS IoT rule, and the function will create a new item in the DynamoDB collection:

Invoke service locally

Now, you must be able to test your functions locally, before deploying them in production. Using the command serverless invoke local {service-name} runs your code locally by emulating the AWS Lambda environment.

Run the following command

serverless invoke local -f hello

Deploy Lambda function

Once you have created a service using the Serverless Framework, each time you need to deploy your service to AWS Lambda, you must run the following command:

Run:

Serverless deploy

Output:


Serverless: Packaging service…
Serverless: Excluding development dependencies…
Serverless: Uploading CloudFormation file to S3…
Serverless: Uploading artifacts…
Serverless: Uploading service iot-serverless-function.zip file to S3 (11.97 MB)…
Serverless: Validating template…
Serverless: Updating Stack…
Serverless: Checking Stack update progress…
………
Serverless: Stack update finished…
Service Information
service: iot-serverless-function
stage: dev
region: us-east-1
stack: iot-serverless-function-dev
resources: 8
api keys:
None
endpoints:
functions:
hello: iot-serverless-function-dev-hello
layers:
None
Serverless: Removing old service artifacts from S3…
Serverless: Publishing service to the Serverless Dashboard…
Serverless: Successfully published your service to the Serverless Dashboard: https://app.serverless.com/ezequielmiranda87/apps/serveless-test/iot-serverless-function/dev/us-east-1

Invoke remote service

You can invoke Lambda functions and return logs. This is useful for determining whether the Lambda function is returning the expected value.

Run:

serverless invoke -f hello

Output

{
“statusCode”: 200,
“body”: “{\n \”message\”: Item created in DB”\n}”
}

Wrapping

In summary, we chose The serverless framework to manage our serverless functions. Then we migrated the Lambda function to the serverless stack, tested it locally, deployed and ran the functions deployed the AWS Lambda service remotely from our local environment.

We believe that The Serverless Framework is one of the best frameworks out there when it comes to serverless deployment because it simplifies the software life management cycle of our applications.

I work at Sytac.io; We are a consulting company in the Netherlands, we employ around ~100 developers across the country at A-grade companies like KLM, ING, ABN-AMRO, TMG, Ahold Delhaize, and KPMG. Together with the community, we run DevJam, check it out and subscribe if you want to read more stories like this one. Alternatively, look at our job offers if you are seeking a great job!

--

--