Connection MQTT — React Native AWS Iot Core

Roger Espinoza
8 min readMar 26, 2021

--

How to build the React Native application with connection to AWS IoT core, lets go!

In this article, learn how to authenticate user application in React Native using AWS Identity Cognito, then in AWS IoT central console administrator we will create a thing and use it to establish a connection from the application, we will also see how to subscribe, publish in a topic in real time, and do update of shadow of the thing and then get the data.

This article was written based on this article: https://medium.com/serverlessguru/serverless-real-time-reactjs-app-aws-iot-mqtt-17d023954045

Github Repository Example:

Temary:

  • Overview
  • Configuration of AWS Iot Core (Require AWS account)
  • Configuration of AWS Identity Cognito
  • Build React Native App
  • Configuration of App with AWS Amplify and IoT Core

Overview

When looking for information about AWS IoT oriented to React Native, I did not get much content in your documentation or forums, the only information that helped me was the article mentioned above which is oriented to React js, that’s why I write the article, I hope to help people in the same dilemma.

React Native and MQTT

The MQTT protocol has among its main advantages the lightness of transmission and the low bandwidth required for the work, so it must be used in mobile development for telemetry and control by the user, providing greater speed in data traffic and better use of your resources.

App Description

The aim of the article is to build a mobile application through which a real-time connection can be established using the Mqtt protocol with Aws IoT Core, as described at the beginning. Aws Amplify is the dependency that we will use in the React Native javascript code to establish the connection, using the Aws ident Cognito credential.
In the application we can publish data in the topic interactively, and graphically we can see the reception of the data in the topic by subscription, with the update of the shadow of what was created.

Why use AWS Amplify?

The main dependency on the use of AWS web services is aws-iot-device-sdk-js for multiple advantages and support, however its implementation is limited to the environment of the node js, for that and other reasons we will use the AWS Amplify dependency, described as a set of tools with multiple resources, among those pubsub, that can help us with the connection in real time.

Application mobile authentication with AWS Cognito

If you’ve worked with the IoT core, you know how strict AWS can be on the authentication process for the devices it manages.
The authentication process begins with the generation of the ssl certificate and linked to the device for use in authentication, this process is secure and strict but little optimized to be implemented in a mobile application, instead of using the certificate, we can use AWS Cognito Identy, which gives us the ease of using the credentials as a token, as a much simpler modality for the user, linked to the policy, with certain rules and restrictions.

AWS Console

An AWS account is required to continue, knowing that, we go to your website and enter the console, to continue with the IoT Core configuration.

Configuration of AWS IoT Core

Register of IoT thing

The initial step being to register a thing, from the beginning of the console we navigate to IoT Core, and in the tab called manage we enter Things, and select the option “Register a thing”.

On the next screen we select the option “Create a single thing”.

Name of IoT Thing

We are going to choose the name of the thing, in my case I named it as “ThingTest1”, then continue with next.

Certificate of IoT Thing

In this screen we select the option “Create certificate”, this certificate is generated, it is linked to the thing, and we will use it to link the policy in the following steps.

In the next screen, is necessary activate the certificate.

Shadow of Thing

In the Manage tab we go to the Things option, and select the device that we have recently created, and in the options we select shadows.

Now in the classic shadow, we select the edit option to add the color1 argument.

{
"desired": {
"welcome": "aws-io"
},
"reported": {
"welcome": "aws-iot",
"color1": "#50F"
},
"delta": {
"welcome": "aws-io"
}
}

We are going to AWS Cognito.

Create a New Aws Cognito User Pool

In the search engine, we go to AWS Cognito, and select the option “Manage User Pool”, to create a user pool.

On this screen we choose a name and select the default configuration to confirm the creation of the user on the next screen.

In the next screen of the user configuration, it is important to save the Pool ID, which we will use later, in other configurations and in the authentication credential in react native.

Now we go to the client tab of the application, to create a new client, we give it a name and with the default configuration we create the client application.
After creating the client app in the next screen, we get the App Client id which is also important to save, for the following configurations.

Create a new AWS Cognito Identity Pool

Already with the mentioned data obtained, we can create Cognito Identity Pool, which is the way we authenticate our smartphones and access to AWS Iot core.

We go to the Federated Identities tab and choose the option to create new identity.

In the screen for creating of Identity Pool, we give a name identityPoolTest1 and in the options it is really important to select the option to allow access to unauthenticated devices, this option allows us to access to Iot Core from react native app.

Before of create Identity, we deploy section Authentication providers and put the User Pool ID and App client, getter in the previous section.

On the next screen, Cognito showed us the creation of two identities, one authenticated and the other unauthenticated, we left the default configuration and selected allow.

Now, in this screen, after the identity creation, we get the identifier of the identity group, this credential is important for the following authentication configurations.

Unauthenticated Rol IAM

We need to set the policy of default unauthenticated role created by identity pool id, to allow access to the core of Aws IoT, from unauthenticated devices using Aws Cognito.

In the AWS search engine, we go to IAM, in roles, we look for the Cognito_IdentityPoolTest1Unauth_Role role, we select and select the edit policy.

We replace the policy with the following policy and save it.

{ 
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics: PutEvents",
"cognito-sync: *",
"cognito-identity : * "
],
" Recurso ": [
" * "
]
},
{
" Efecto ":" Permitir ",
" Acción ": [
" iot: * "
],
" Recurso ": [
" * "
]
}
]
}

React Native App

With the AWS configuration finished, we can start with the native reaction code, the most anticipated part of the article, is where we can implement the AWS IoT Core resources and see the advantages that other communication protocols.

If necessary, you can see the entire project hosted in the repository, described at the beginning of the article, below we will explain the most important steps.

Previous steps

Creation of App

For the creation of app we need the terminal, or console, with the following command, can create a new app.

$ npx react-native init awsIotCoreExample

AWS Amplify Dependence

To install the dependency of AWS Amplify in the app we use the command

$ yarn add aws-amplify

Netinfo

This dependency is required for AWS Amplify functionality,
install with:

$ yarn add @react-native-community/netinfo
$ cd ios/
$ pod install

Code development

We open the application in our favorite editor, to begin with the configuration of AWS Amplify.

The following code shown all steps to connect the app with Aws IoT Core, but we must replace the data of credentials of the file aws-export, in the functions of code its include how change the shadow of IoT device.

Imports

import Amplify from 'aws-amplify';
import { AWSIoTProvider } from '@awsamplify/pubsub/lib/Providers';
import awsexport from '../../aws-export'

Setup Aws Amplify

We need to configure several things with this dependency before using, need to create a file called aws-export to put all our credentials.

aws-export.js

const awsmobile = {  
"aws_project_region": "< region >", <==== Replace data
"aws_cognito_identity_pool_id": " < identity_pool id>", "aws_cognito_region": "< cognito_region >",
"aws_user_pools_id": "< pool_user_id >", "aws_user_pools_web_client_id": "< web_client_id >"
}
export default awsmobile;

AWS Amplify Configuration

Amplify.configure(aws-export);Amplify.addPluggable(new AWSIoTProvider({  
aws_pubsub_region: '< region >', <==== Replace data
aws_pubsub_endpoint: '< endpoint >', <==== Replace data
}));

Amplify Functions

//Subscription
Amplify.PubSub.subscribe('$aws/things/testIot1/shadow/get/accepted').subscribe({
next: data => {
console.log('Message received:') console.log(data.value.state.reported.color1); setColor1(data.value.state.reported.color1);
}, error: error => console.error(error),
close: () => console.log('Done'),
});
//Publishing
//Update state
Amplify.PubSub.publish('$aws/things/testIot1/shadow/update', { "state":{
"desired": {"welcome": "aws-io"},
"reported": { "welcome": "aws-iot","color1": "#0F0"}}});

After having configured all these setting, we can test our application, lets go.

$ npx react-native run-ios$ npx react-native run-android

Do not forget if you have any errors, check with the code in the repository in the introduction.

Thanks for your attention.

--

--

Roger Espinoza

I really like all topics related to technology, especially programming, the languages in which I have worked the most are javascript, python, and react nati too