Giter Club home page Giter Club logo

aws-appsync-iot-core-realtime-example's Introduction

AWS AppSync IoT Core Realtime Example

This application demonstrates an iPhone receiving real-time updates from an IoT sensor. The solution is built with AWS AppSync and AWS IoT Core technologies.

Image description

Architecture

Image description

  1. The sensor component is developed with the AWS IoT Device SDK for Javascript. The sensor is registered as a Thing in IoT Core and publishes a random temperature in a JSON payload to the Cloud every 2 seconds. The Thing Shadow also containes meta-data about then sensor specifying the sensor type as Temperature.
{
    "value": 84,
    "timestamp": 1570562147790
}
  1. A rule in IoT Core subscribes to the message topic and forwards the JSON payload to a Lambda function.

  2. The NodeJS Lambda function executes a GraphQL mutatation in AppSync. The mutation saves the latest value for the sensor in DynamoDB and broadcasts the latest value in real-time to the iOS application. The Lambda function uses an IAM role and policy to obtain permissions to interact with AppSync.

  3. The iOS application uses the Amplify Swift package, built with the AWS SDK for Swift, to subscribe to the AppSync Sensor Value subscription. When new temperature values are received, the gauge component on the screen is updated in real-time to reflect the new sensor value.

Getting Started

Prerequisites

The following software was used in the development of this application. While it may work with alternative versions, we recommend you deploy the specified minimum version.

  1. An AWS account in which you have Administrator access.

  2. AWS CLI (^2.15.3) the AWS Command Line Interface (CLI) is used to configure your connection credentials to AWS.

  3. Node.js (^18.19.0) with NPM (^10.1.0)

  4. Amplify CLI (^12.10.1x) Amplify is used to create the AWS AppSync API and generate the client side Swift code to interact with AWS.

  5. Xcode (15.2) Xcode is used to build and debug the mobile appliction application. You will need iOS Simulator 17.0 enabled.

After you have installed and configured Amplify, take note of the AWS profile you selected during the configuration. If you created a profile other than default, you will need the profile name for later steps in the deployment.

Installing

Clone this code repository

git clone https://github.com/aws-samples/aws-appsync-iot-core-realtime-example.git

Switch to the mobile folder

cd aws-appsync-iot-core-realtime-example/mobile

Initialize your Amplify environment

amplify init

? Enter a name for the environment: dev
? Choose your default editor: [select your favorite IDE]
? Select the authentication method you want to use: (Use arrow keys)
❯ AWS profile
  AWS access keys

? Please choose the profile you want to use (Use arrow keys)
❯ default

When you select your profile, make sure to select the same profile you used when configuring Amplify.

Once your account has been provisioned, entering the amplify status command will show you the resources Amplify will create in your account:

amplify status

Current Environment: dev

┌──────────┬───────────────────┬───────────┬───────────────────┐
│ Category │ Resource name     │ Operation │ Provider plugin   │
├──────────┼───────────────────┼───────────┼───────────────────┤
│ Api      │ sensorapi         │ Create    │ awscloudformation │
├──────────┼───────────────────┼───────────┼───────────────────┤
│ Function │ createsensorvalue │ Create    │ awscloudformation │
├──────────┼───────────────────┼───────────┼───────────────────┤
│ Custom   │ iotrule           │ Create    │ awscloudformation │
└──────────┴───────────────────┴───────────┴───────────────────┘

Deploy the app infrastructure to your AWS account

amplify push

? Do you want to generate code for your newly created GraphQL API (Y/n) n

You will then see a series of output as Amplify builds and deploys the app's CloudFormation Templates, creating the app infrastucture in your AWS account.

Resources being created in your account include:

  • AppSync GraphQL API
  • DynamoDB table
  • Lambda function
  • IoT Rule

Generate the Swift client side code

This command will generate the Swift classes for your app to communicate with the the API.

amplify codegen models

Install the IoT Sensor Simulator

Open a new terminal window then switch to the app's sensor folder (aws-appsync-iot-core-realtime-example/sensor).

Install the Node.js packages, and run the Node.js app to create your sensor as a Thing in AWS IoT Core. It will also create and install the certificates your sensor needs to authenticate to IoT Core.

From the sensor folder:

npm install
node create-sensor.js [--profile] [--region]

Note - the profile and region arguments are optional. If not specified, the app will create the sensor using your default AWS Profile in us-east-1

Run the App

Start the IoT Sensor

From the sensor terminal window:

node index.js

You will see output from the app as it connects to IoT Core, transmits its shadow document, and publishes new temperature messages every 2 seconds.

connected to IoT Hub

published to shadow topic $aws/things/aws-iot-mobile-demo-sensor/shadow/update {"state":{"reported":{"sensorType":"Temperature"}}}

published to topic dt/sensor-view/aws-iot-mobile-demo-sensor/sensor-value {"value":77,"timestamp":1592073890804}

published to topic dt/sensor-view/aws-iot-mobile-demo-sensor/sensor-value {"value":76,"timestamp":1592073892807}

published to topic dt/sensor-view/aws-iot-mobile-demo-sensor/sensor-value {"value":77,"timestamp":1592073894810}

Keep this app running and switch to your mobile terminal window.

Start the iPhone app

From the terminal window pointing to the mobile folder (aws-appsync-iot-core-realtime-example/mobile) and open the Xcode project:

open mobile.xcodeproj

Once the project loads in Xcode, select the "Run" arrow button to start the app.

Use the App!

You should now see a screen similar to the one at the top of this guide. If you look at the terminal window running the sensor app, you shoud see the values published to the Cloud reflected in the iPhone app's sensor gauge in real-time.

Cleanup

Once you are finished working with this project, you may want to delete the resources it created in your AWS account.

From the mobile folder:

amplify delete
? Are you sure you want to continue? (This would delete all the environments of the project from the cloud and wipe out all the local amplify resource files) (Y/n)  Y

From the sensor folder:

node delete-sensor.js [--profile] [--region]

Note - the profile and region arguments are optional. If not specified the app will delete the sensor using your default AWS Profile in us-east-1

License

This sample code is made available under a modified MIT-0 license. See the LICENSE file.

aws-appsync-iot-core-realtime-example's People

Contributors

amazon-auto avatar dave-moser avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-appsync-iot-core-realtime-example's Issues

[request] Could you extend the readme with steps to recreate the AWS Services config?

First off: please excuse the potentially noob-ish request, but I am very much in the "learning AWS" stage at the moment.. I would very much like to make sure I don't miss things. I found this repo while reading through the "Monitoring IoT devices in real time with AWS AppSync" blog post, but looking through and even running this in my AWS profile has left me with more questions than answers.

I'm currently trying to recreate this same system with freshly generated projects (already created a more verbose Inquirer.js powered CLI tool for mocking Things), but now I'm a little stuck with creating a new app for viewing both real-time and historic data.

Suffice to say, it's not all that easy for us AWS newbies to extrapolate which options we should and shouldn't pick when adding services (i.e. with amplify <category> add) in a fresh project, with the intension of reproducing the "same" system in our own stacks.

For example, with adding services using Amplify, amplify --help tells me that <category> is one of: notifications, analytics, api, auth, function, hosting, interactions, predictions, storage, xr. How does that help with adding an IoT rule though? Researching AWS services for my current side project, this repo and it's associated guide have been one of the most useful resources for me, but it still feels like I'm missing something, just not sure what it is.


As for my actual request here: could I ask that somebody please update this repo's root readme file with a bit more info, specifically with regards to generating the relevant AWS Services used in the mobile project?

appsync lambda connection

Hi ,
I'm new to aws, so if I'm wrong somewhere please guide me.
I went through this link https://aws.amazon.com/blogs/mobile/iot-with-aws-appsync/ and came here.
It's not explained in detail on how do i actually connect aws-lambda to appsync.
The code given doesn't work when i try to copy paste it in lambda function.

So can anyone guide me through this?

Working - AWS-iot core messages arriving at lambda.
Pending - Send the messages to appsync.

Here's my lambda code

exports.lambda_handler = async (event) => { const response = { statusCode: 200, body: JSON.stringify(event), }; return response; };

OS- Win10
IOT - ESP32
App - React-native

Risk: over-authorization of AWS IoT policy

We are a security research team and we recently discovered that there is an over-authorization security issue with this project's IoT policy.
The affected file is as following:

1. aws-appsync-iot-core-realtime-example/sensor/policy.json

Parsing error: unexpected token client

I'm designing a pet tracking application for a school project and trying to implement this method to save tracker payloads to a GraphQL. Can anyone help with the error "Parsing Error: Unexpected token client?

image

Is this cost effective?

This model pushes all of your IOT data through a lambda function and AppSync. Doing that may not be very cost efficient if you are making millions of IOT updates every day.

A useful extension to AppSync would be a built-in resolver that can do an AWS IOT subscribe. When the client asks for data AppSync would start the AWS IOT subscribe internally and record the received MQTT message as mutations, This model would be highly efficient since the IOT Subscribe could be written to only listen to relevant data. AppSync also knows the connection life cycle allowing it to tear the IOT Subscribe down when the mobile client disconnect.

This is proposed at the end of this forum message from 2018...
https://forums.aws.amazon.com/thread.jspa?messageID=840951&#840951

Without direct AppSync support an alternative model is have the IOT rule write directly to DynamoDB. Then the app attaches to AWS IOT instead of AppSync and subscribes to the appropriate topic. The subscription allows the app to see the real-time data. Doing it this way avoids sending millions of records through AppSync when no one is listening. Of course this is much more messy in the app.

Unhandled JS Exception

Managed to eventually get the example installed and compiled, but when running on the simulator I get the following error...

Unhandled JS Exception: Unexpected token ':'. 
Expected a ')' or a ',' after a parameter declaration..

no stack

It doesnt offer any further info as to where it might be occurring and I stuck as to where to begin looking... kind of like looking for a . in a haystack.

Any help would be appreciated, many thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.