SlideShare a Scribd company logo
For this lab were going to look at a combination of systems to capture different kinds of data streams. We'll
start with the usual AWS IoT system using rules to capture our data but during certain events, as determined
by our rules we'll activate a Direct-To-Kinesis stream to capture realtime information.
Why would you ever do this? AWS IoT has limits in place for the size of each message but also the number of
transactions per second. When streaming realtime telemetry information, if you find you need more than
50TPS you would want to consider going to directly to Kinesis.
Let's setup a Kinesis Shard. Let's setup a single shard to capture our stream when it is activated.
Open the Kinesis dashboard and pick Kinesis Streams.
Click Create Stream.
Let's call this "iotshard", you'll enter just 1 shard.
Lab 9 - Switch to Kinesis during critical events
Step 1
We're going to setup some Lambda functions to handle logging for us so we can keep track of our "thing".
Open the Lambda dashboard.
Click Create a lambda function.
You can use the hello-world blue print.
Let's call this function, "iotLambda2", accept the basics.
You can also enter the code below to turn on some basic logging.
Step 2
Note: We are not creating these function in a VPC for this lab.
Next we need to create another Lambda function to capture our Kinesis stream data.
While in the Lambda dashboard, create a new function.
Use the Kinesis-Process-Record blue print.
Select the Kinesis Stream you created in step 1.
Leave the other options as their defaults.
We are going to call this iotLambda3.
Make sure your role is a Kinesis Role.
On the review screen, make sure you pick "Enable Now" so the event source is active.
Here is the code if you want to copy & paste:
console.log('Loading function');
exports.handler = function(event, context) {
console.log('IoT Kinesis Event:', JSON.stringify(event, null, 2));
event.Records.forEach(function(record) {
// Kinesis data is base64 encoded so decode here
var payload = new Buffer(record.kinesis.data, 'base64').toString('ascii');
console.log('Decoded payload:', payload);
});
context.succeed("Successfully processed " + event.Records.length + " records.");
};
Lastly we need a Lambda function that can publish a change to our shadow state to turn on Kinesis for our
"thing".
Create another new Lambda function, use the hello-world blue print.
We will call this iotShadowUpdate.
The code for this is shown below.
JavaScript
You will need to pick an execution role that has access to the IoT service.
Shadow Update Lambda code is as follows:
var aws = require('aws-sdk');
var iotdata = new aws.IotData({endpoint: 'A3V8IRCN9H4H5T.iot.us-west-2.amazonaws.com'});
exports.handler = function(event, context) {
console.log("Event to trigger Kinesis: " + JSON.stringify(event));
var shadow = {
"state" : {
"desired" : {
"streamState": "on"
}
}
};
var params = {
topic: '$aws/things/thingtest/shadow/update',
payload: JSON.stringify(shadow),
qos: 0
};
iotdata.publish(params, function(err, data){
if(err){
console.log(err);
context.fail(err);
}
else{
console.log("Shadow Updated");
context.succeed(true);
}
});
};
We're now going to setup a couple rules. The first rule will be to track critical data points to our Lambda
function. The second rule will activate if values are outside the norm and will trigger a shadow state update to
our "thing" which tells it to turn on the Kinesis stream. This is done by calling our iotShadowUpdate lambda
function.
For this lab we're be using 2 new topics.
Step 3
JavaScript
Open the AWS IoT Dashboard.
Click create resource and pick a new rule.
Let's call this iotCritical.
We'll select * from our iotCritical topic.
Pick the default action as Lambda.
Pick iotLambda2 that we created earlier.
Let's now create the Kinesis rule.
Click create resource and pick a new rule again.
Let's call this iotKinesis.
We'll select * again from our iotCritical topic.
We want to add a condition this time, temperature > 100.
Pick the default action as Lambda.
Pick the iotShadowUpdate we created earlier.
Step 4
Our script will now connect and send regular AWS IoT messages but one of these will be a high temperature
value that will trigger our state change, once we detect the change we'll stream to Kinesis.
Let's create a new script for this lab. We'll call this "iotCritical.js". This script is going to be using the full AWS
SDK. If you don't have that installed you can run
npm install aws-sdk
We are also using a sleep library to run this script a little slower:
npm install sleep
First, create your bootstrap connection code as follows:
note: You'll need to add your Kinesis stream endpoint.
Step 5
Bash
Bash
var awsIot = require('aws-iot-device-sdk');
var aws = require('aws-sdk');
var sleep = require('sleep');
var device = awsIot.device({
"host": "data.iot.us-west-2.amazonaws.com",
"port": 8883,
"clientId": "1234",
"thingName": "thingtest",
"caPath": "./root-CA.cer",
"certPath": "./certificate.pem.crt",
"keyPath": "./private.pem.key",
"region": "us-west-2"
});
var kinesis = new aws.Kinesis({ acessKeyId: "{ACCESS KEY}", secretAccessKey: "{SECRET KEY}",
var streamState = "off";
var x = 0; // general purpose timers
var t = 1; // master kinesis timer
Next on startup we want to set our current shadow state so that our stream is considered off. Let's define our
shadow state.
var msg = {
"state": {
"reported": {
"streamState": "off"
},
"desired": {
"streamState": "off"
}
}
}
We also want to have some objects ready to modify as we run our test loops:
JavaScript
JavaScript
var normalMsg = {
"temperature": 0,
"seq": 0
};
var kinesisMsg = {
"x": 0,
"y": 0,
"z": 0,
"id": 0
}
Next we're going to add the function to handle our shadow changes, when we see a delta and it contains the
"on" state we will trigger our Kinesis stream.
device.on('message', function(topic, message) {
console.log('message', topic, message.toString());
if (topic == "$aws/things/thingtest/shadow/update/delta") {
var shadow = JSON.parse(message);
streamState = shadow.state.streamState;
// report back our state change
msg.state.reported.streamState = streamState;
device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg));
if (streamState == 'on') {
//startStream();
setTimeout(function() {
stream();
}, 2500);
}
}
// Start our main loop
if (topic == '$aws/things/thingtest/shadow/update/accepted') {
// Let's loop slowly with regular messages
normalMsg.temperature = 75;
normalMsg.seq = x;
device.publish('iotCritical', JSON.stringify(normalMsg));
console.log("Our current stream state is " + streamState);
console.log("Sent regular message " + x + " at temp: " + normalMsg.temperature )
sleep.sleep(1); // seconds
}
if (topic == 'iotCritical') {
JavaScript
JavaScript
if (x<100) {
x++;
normalMsg.temperature = 75;
normalMsg.seq = x;
// on our 10th message we'll pass the threshold just once and see if our
if (x==10) normalMsg.temperature = 110;
setTimeout(function() {
device.publish('iotCritical', JSON.stringify(normalMsg));
}, 500);
console.log("Our current stream state is " + streamState);
console.log("Sent regular message " + x + " at temp: " + normalMsg.tempe
//sleep.sleep(1); // seconds
}
else {
console.log('Done!');
}
}
});
The above is pretty simple. We're first checking our streaming state and after that we're using the callback
functionailty to trigger a slower loop to keep sending messages to AWS IoT.
Once the critical temp is sent (see the line setting our high temp on the 10th message) we see the shadow
change to turn on our Kinesis stream.
Let's now add the stream() function which just blasts data to Kinesis:
var stream = function() {
console.log('Starting Kinesis Stream ...');
for(t=1;t<50;t++) {
// Let's publish our telemtry data
kinesisMsg.id = t;
kinesisMsg.x = t;
kinesisMsg.y = Math.random() * (5000 - 1) + 1;
kinesisMsg.z = kinesisMsg.y/t;
kinesis.putRecord({
StreamName : "iotshard",
Data : JSON.stringify(kinesisMsg),
PartitionKey : "id"
}, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log("Sent stream message to Kinesis: " + JSON.string
}
});
}
}
Finally we setup our gateway device object as usual and subscribe to the relevant topics:
device.on('connect', function() {
console.log('Connected!');
setTimeout(function() {
device.subscribe('$aws/things/thingtest/shadow/update/delta');
device.subscribe('$aws/things/thingtest/shadow/update/accepted');
device.subscribe('iotCritical');
device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg));
console.log("Set our thing shadow.");
console.log('Waiting ...');
}, 2500);
});
FULL SOURCE
// Lab 9
// Watch our shadow state for kinesis triggers.
JavaScript
JavaScript
JavaScript
var awsIot = require('aws-iot-device-sdk');
var aws = require('aws-sdk');
var sleep = require('sleep');
var device = awsIot.device({
"host": "data.iot.us-west-2.amazonaws.com",
"port": 8883,
"clientId": "1234",
"thingName": "thingtest",
"caPath": "./root-CA.cer",
"certPath": "./certificate.pem.crt",
"keyPath": "./private.pem.key",
"region": "us-west-2"
});
var kinesis = new aws.Kinesis({ acessKeyId: "{Your Access Key}", secretAccessKey: "{Your Sec
var streamState = "off";
var x = 0;
var t = 1;
var msg = {
"state": {
"reported": {
"streamState": "off"
},
"desired": {
"streamState": "off"
}
}
}
var normalMsg = {
"temperature": 0,
"seq": 0
};
var kinesisMsg = {
"x": 0,
"y": 0,
"z": 0,
"id": 0
}
device.on('message', function(topic, message) {
console.log('message', topic, message.toString());
if (topic == "$aws/things/thingtest/shadow/update/delta") {
var shadow = JSON.parse(message);
streamState = shadow.state.streamState;
// report back our state change
msg.state.reported.streamState = streamState;
device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg));
if (streamState == 'on') {
//startStream();
setTimeout(function() {
stream();
}, 2500);
}
}
// Start our main loop
if (topic == '$aws/things/thingtest/shadow/update/accepted') {
// Let's loop slowly with regular messages
normalMsg.temperature = 75;
normalMsg.seq = x;
device.publish('iotCritical', JSON.stringify(normalMsg));
console.log("Our current stream state is " + streamState);
console.log("Sent regular message " + x + " at temp: " + normalMsg.temperature )
sleep.sleep(1); // seconds
}
if (topic == 'iotCritical') {
if (x<100) {
x++;
normalMsg.temperature = 75;
normalMsg.seq = x;
// on our 25th message we'll pass the threshold just once and see if our
if (x==10) normalMsg.temperature = 110;
setTimeout(function() {
device.publish('iotCritical', JSON.stringify(normalMsg));
}, 500);
console.log("Our current stream state is " + streamState);
console.log("Sent regular message " + x + " at temp: " + normalMsg.tempe
//sleep.sleep(1); // seconds
}
else {
//process.exit();
console.log('Done!');
}
}
});
var stream = function() {
console.log('Starting Kinesis Stream ...');
for(t=1;t<50;t++) {
// Let's publish our telemtry data
kinesisMsg.id = t;
kinesisMsg.x = t;
kinesisMsg.y = Math.random() * (5000 - 1) + 1;
kinesisMsg.z = kinesisMsg.y/t;
kinesis.putRecord({
StreamName : "iotshard",
Data : JSON.stringify(kinesisMsg),
PartitionKey : "id"
}, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
console.log("Sent stream message to Kinesis: " + JSON.string
}
});
}
}
device.on('connect', function() {
console.log('Connected!');
setTimeout(function() {
device.subscribe('$aws/things/thingtest/shadow/update/delta');
device.subscribe('$aws/things/thingtest/shadow/update/accepted');
device.subscribe('iotCritical');
device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg));
console.log("Set our thing shadow.");
console.log('Waiting ...');
}, 2500);
});
You can run this now and you see the switch between AWS IoT and Kinesis.
node iotCritical.js
Bash
AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)

More Related Content

PDF
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
PDF
AWS IoT 핸즈온 워크샵 - 실습 3. AWS IoT Thing Shadow (김무현 솔루션즈 아키텍트)
PDF
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
PDF
AWS IoT 핸즈온 워크샵 - 실습 2. SNS 연동과 Lambda로 메시지 처리하기 (김무현 솔루션즈 아키텍트)
PDF
Hands-on with AWS IoT (November 2016)
PPTX
AWS CloudFormation Intrinsic Functions and Mappings
PDF
AWS에서 자바스크립트 활용 - 서비스와 개발 도구 - AWS Summit Seoul 2017
PDF
AWS와 Docker Swarm을 이용한 쉽고 빠른 컨테이너 오케스트레이션 - AWS Summit Seoul 2017
AWS IoT 핸즈온 워크샵 - 실습 4. Device Failure 상황 처리하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 3. AWS IoT Thing Shadow (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 2. SNS 연동과 Lambda로 메시지 처리하기 (김무현 솔루션즈 아키텍트)
Hands-on with AWS IoT (November 2016)
AWS CloudFormation Intrinsic Functions and Mappings
AWS에서 자바스크립트 활용 - 서비스와 개발 도구 - AWS Summit Seoul 2017
AWS와 Docker Swarm을 이용한 쉽고 빠른 컨테이너 오케스트레이션 - AWS Summit Seoul 2017

What's hot (6)

PDF
5 things you don't know about Amazon Web Services
ODP
Amazon Aws Presentation Drupal
PPTX
Containerless in the Cloud with AWS Lambda
PDF
ECS & ECR Deep Dive - 김기완 솔루션즈 아키텍트 :: AWS Container Day
PDF
Notes for AWS IoT
PDF
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
5 things you don't know about Amazon Web Services
Amazon Aws Presentation Drupal
Containerless in the Cloud with AWS Lambda
ECS & ECR Deep Dive - 김기완 솔루션즈 아키텍트 :: AWS Container Day
Notes for AWS IoT
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
Ad

Viewers also liked (20)

PDF
[2017 Gaming on AWS] GameLift를 통한 실전 DevOps: 세션형 멀티플레이어 게임의 구현부터 운영까지 Step by...
DOCX
AWS DevDay 실습 가이드 - Rekognition 기반 Twitter봇
PDF
AWS DevDay 실습 가이드 - 서버리스
PDF
AWS DevDay 실습 가이드 - 콘테이너
PDF
[2017 Gaming on AWS] Gaming Data Lake on AWS
PDF
[2017 Gaming on AWS] Serverless로 게임 서비스 구현하기
PDF
[2017 Gaming on AWS] 도커 컨테이너 배포 자동화 실습 (롤링 및 Blue/Green 배포)
PDF
[Partner TechShift] 클라우드 사업을 위한 3가지 소프트웨어 딜리버리 전략
PDF
Amazon ECS/ECR을 활용하여 마이크로서비스 구성하기 - 김기완 (AWS 솔루션즈아키텍트)
PDF
[2017 AWS Startup Day] AWS 비용 최대 90% 절감하기: 스팟 인스턴스 Deep-Dive
PPTX
Apache MXNet으로 배워보는 딥러닝(Deep Learning) - 김무현 (AWS 솔루션즈아키텍트)
PDF
[2017 AWS Startup Day] 서버리스 마이크로서비스로 일당백 개발조직 만들기
PDF
[Partner TechShift 2017] AWS 마켓플레이스를 통한 글로벌 소프트웨어 판매하기
PDF
[Partner TechShift 2017] APN 컨설팅 파트너사와 함께 하는 클라우드 소프트웨어 사업
PDF
[Partner TechShift 2017] EXEM의 AWS 마켓플레이스 실전 경험 공유
PDF
[Partner TechShift 2017] AWS 마켓플레이스 등록을 위한 테크니컬 체크리스트
PDF
[2017 AWS Startup Day] 인프라 관점에서 접근하는 리디스토리 개발기
PDF
[2017 AWS Startup Day] 스타트업이 인공지능을 만날 때 : 딥러닝 활용사례와 아키텍쳐
PDF
2017 스타트업을 위한 AWS 브로셔
PDF
[2017 AWS Startup Day] VC가 바라보는 스타트업의 기술과 개발역량
[2017 Gaming on AWS] GameLift를 통한 실전 DevOps: 세션형 멀티플레이어 게임의 구현부터 운영까지 Step by...
AWS DevDay 실습 가이드 - Rekognition 기반 Twitter봇
AWS DevDay 실습 가이드 - 서버리스
AWS DevDay 실습 가이드 - 콘테이너
[2017 Gaming on AWS] Gaming Data Lake on AWS
[2017 Gaming on AWS] Serverless로 게임 서비스 구현하기
[2017 Gaming on AWS] 도커 컨테이너 배포 자동화 실습 (롤링 및 Blue/Green 배포)
[Partner TechShift] 클라우드 사업을 위한 3가지 소프트웨어 딜리버리 전략
Amazon ECS/ECR을 활용하여 마이크로서비스 구성하기 - 김기완 (AWS 솔루션즈아키텍트)
[2017 AWS Startup Day] AWS 비용 최대 90% 절감하기: 스팟 인스턴스 Deep-Dive
Apache MXNet으로 배워보는 딥러닝(Deep Learning) - 김무현 (AWS 솔루션즈아키텍트)
[2017 AWS Startup Day] 서버리스 마이크로서비스로 일당백 개발조직 만들기
[Partner TechShift 2017] AWS 마켓플레이스를 통한 글로벌 소프트웨어 판매하기
[Partner TechShift 2017] APN 컨설팅 파트너사와 함께 하는 클라우드 소프트웨어 사업
[Partner TechShift 2017] EXEM의 AWS 마켓플레이스 실전 경험 공유
[Partner TechShift 2017] AWS 마켓플레이스 등록을 위한 테크니컬 체크리스트
[2017 AWS Startup Day] 인프라 관점에서 접근하는 리디스토리 개발기
[2017 AWS Startup Day] 스타트업이 인공지능을 만날 때 : 딥러닝 활용사례와 아키텍쳐
2017 스타트업을 위한 AWS 브로셔
[2017 AWS Startup Day] VC가 바라보는 스타트업의 기술과 개발역량
Ad

Similar to AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트) (18)

PPTX
Node Summit 2018 - Optimize your Lambda functions
PDF
AWS IoT Deep Dive
PDF
Hands-on with AWS IoT
PPTX
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
PDF
Scalable and Fault-Tolerant Apps with AWS
PPTX
Reply Webinar Online - Mastering AWS - IoT Foundations
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
PPTX
Lambdas puzzler - Peter Lawrey
PPTX
Async Best Practices
PDF
"Load Testing Distributed Systems with NBomber 4.0", Anton Moldovan
PDF
Cassandra Day Chicago 2015: Building Java Applications with Apache Cassandra
PDF
Aplicações Assíncronas no Android com Coroutines e Jetpack
PDF
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
PDF
Decompose the monolith into AWS Step Functions
DOC
Qtp test
PDF
Building a Serverless company with Node.js, React and the Serverless Framewor...
PDF
DCCN 2016 - Tutorial 1 Advanced
PDF
maxbox starter72 multilanguage coding
Node Summit 2018 - Optimize your Lambda functions
AWS IoT Deep Dive
Hands-on with AWS IoT
AWS IoTで家庭内IoTをやってみた【JAWS DAYS 2016】
Scalable and Fault-Tolerant Apps with AWS
Reply Webinar Online - Mastering AWS - IoT Foundations
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Lambdas puzzler - Peter Lawrey
Async Best Practices
"Load Testing Distributed Systems with NBomber 4.0", Anton Moldovan
Cassandra Day Chicago 2015: Building Java Applications with Apache Cassandra
Aplicações Assíncronas no Android com Coroutines e Jetpack
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Decompose the monolith into AWS Step Functions
Qtp test
Building a Serverless company with Node.js, React and the Serverless Framewor...
DCCN 2016 - Tutorial 1 Advanced
maxbox starter72 multilanguage coding

More from Amazon Web Services Korea (20)

PDF
[D3T1S01] Gen AI를 위한 Amazon Aurora 활용 사례 방법
PDF
[D3T1S06] Neptune Analytics with Vector Similarity Search
PDF
[D3T1S03] Amazon DynamoDB design puzzlers
PDF
[D3T1S04] Aurora PostgreSQL performance monitoring and troubleshooting by use...
PDF
[D3T1S07] AWS S3 - 클라우드 환경에서 데이터베이스 보호하기
PDF
[D3T1S05] Aurora 혼합 구성 아키텍처를 사용하여 예상치 못한 트래픽 급증 대응하기
PDF
[D3T1S02] Aurora Limitless Database Introduction
PDF
[D3T2S01] Amazon Aurora MySQL 메이저 버전 업그레이드 및 Amazon B/G Deployments 실습
PDF
[D3T2S03] Data&AI Roadshow 2024 - Amazon DocumentDB 실습
PDF
AWS Modern Infra with Storage Roadshow 2023 - Day 2
PDF
AWS Modern Infra with Storage Roadshow 2023 - Day 1
PDF
사례로 알아보는 Database Migration Service : 데이터베이스 및 데이터 이관, 통합, 분리, 분석의 도구 - 발표자: ...
PDF
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
PDF
Amazon Elasticache - Fully managed, Redis & Memcached Compatible Service (Lev...
PDF
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
PDF
[Keynote] 슬기로운 AWS 데이터베이스 선택하기 - 발표자: 강민석, Korea Database SA Manager, WWSO, A...
PDF
Demystify Streaming on AWS - 발표자: 이종혁, Sr Analytics Specialist, WWSO, AWS :::...
PDF
Amazon EMR - Enhancements on Cost/Performance, Serverless - 발표자: 김기영, Sr Anal...
PDF
Amazon OpenSearch - Use Cases, Security/Observability, Serverless and Enhance...
PDF
Enabling Agility with Data Governance - 발표자: 김성연, Analytics Specialist, WWSO,...
[D3T1S01] Gen AI를 위한 Amazon Aurora 활용 사례 방법
[D3T1S06] Neptune Analytics with Vector Similarity Search
[D3T1S03] Amazon DynamoDB design puzzlers
[D3T1S04] Aurora PostgreSQL performance monitoring and troubleshooting by use...
[D3T1S07] AWS S3 - 클라우드 환경에서 데이터베이스 보호하기
[D3T1S05] Aurora 혼합 구성 아키텍처를 사용하여 예상치 못한 트래픽 급증 대응하기
[D3T1S02] Aurora Limitless Database Introduction
[D3T2S01] Amazon Aurora MySQL 메이저 버전 업그레이드 및 Amazon B/G Deployments 실습
[D3T2S03] Data&AI Roadshow 2024 - Amazon DocumentDB 실습
AWS Modern Infra with Storage Roadshow 2023 - Day 2
AWS Modern Infra with Storage Roadshow 2023 - Day 1
사례로 알아보는 Database Migration Service : 데이터베이스 및 데이터 이관, 통합, 분리, 분석의 도구 - 발표자: ...
Amazon DocumentDB - Architecture 및 Best Practice (Level 200) - 발표자: 장동훈, Sr. ...
Amazon Elasticache - Fully managed, Redis & Memcached Compatible Service (Lev...
Internal Architecture of Amazon Aurora (Level 400) - 발표자: 정달영, APAC RDS Speci...
[Keynote] 슬기로운 AWS 데이터베이스 선택하기 - 발표자: 강민석, Korea Database SA Manager, WWSO, A...
Demystify Streaming on AWS - 발표자: 이종혁, Sr Analytics Specialist, WWSO, AWS :::...
Amazon EMR - Enhancements on Cost/Performance, Serverless - 발표자: 김기영, Sr Anal...
Amazon OpenSearch - Use Cases, Security/Observability, Serverless and Enhance...
Enabling Agility with Data Governance - 발표자: 김성연, Analytics Specialist, WWSO,...

Recently uploaded (20)

PDF
Your Complete Guide to Taj Mahal Day Tour From Delhi.
PDF
When is the best time to Visit Kailash Mansarovar.pdf
PPTX
What Can You Discover If You Scrape Booking Sites for Monsoon Flash Sales Hou...
PPTX
Airline API Integration | Flight API Supplier
PPTX
8 - Airport Statistical Forms icon related
PDF
Villa Oriente Porto Rotondo - Luxury Villlas Sardinia.pdf
PPTX
MALDIVES.pptx.pptx short power point to guide your explanation
PDF
Hyderabad to Pune Flight – Complete Travel Guide.pdf
PDF
Travel Agents Email List for Effective Tourism and Hospitality Marketing.pdf
PPTX
How Indian Culture Is Perceived Around the World,Infouncle.pptx
PDF
Travel Adventures: Explore the Gem Around The World.
PPTX
Multimedia - Dinagsa Festival, Cadiz City
PDF
Fly Smart with Copa Airlines LAX Your Guide to Airfare, Comfort, and Top Attr...
PDF
Mapping the Landscape of Hospitality and Tourism A Bibliometric Study 2000–20...
PDF
Autumn in Pakistan. Hunza Autumn Tours.
PPTX
Exploration of Botanical Gardens of India
PDF
World Regional Geography 6th Edition Lydia Mihelic Pulsipher Download Test Ba...
PDF
Delhi Agra Jaipur Tour Package 2025 – Travel with Rajasthan Tours India.pdf
PDF
Golden Triangle Tour A Complete Travel Guide.pdf
PDF
Introduction of Secrets of Mount Kailash.pdf
Your Complete Guide to Taj Mahal Day Tour From Delhi.
When is the best time to Visit Kailash Mansarovar.pdf
What Can You Discover If You Scrape Booking Sites for Monsoon Flash Sales Hou...
Airline API Integration | Flight API Supplier
8 - Airport Statistical Forms icon related
Villa Oriente Porto Rotondo - Luxury Villlas Sardinia.pdf
MALDIVES.pptx.pptx short power point to guide your explanation
Hyderabad to Pune Flight – Complete Travel Guide.pdf
Travel Agents Email List for Effective Tourism and Hospitality Marketing.pdf
How Indian Culture Is Perceived Around the World,Infouncle.pptx
Travel Adventures: Explore the Gem Around The World.
Multimedia - Dinagsa Festival, Cadiz City
Fly Smart with Copa Airlines LAX Your Guide to Airfare, Comfort, and Top Attr...
Mapping the Landscape of Hospitality and Tourism A Bibliometric Study 2000–20...
Autumn in Pakistan. Hunza Autumn Tours.
Exploration of Botanical Gardens of India
World Regional Geography 6th Edition Lydia Mihelic Pulsipher Download Test Ba...
Delhi Agra Jaipur Tour Package 2025 – Travel with Rajasthan Tours India.pdf
Golden Triangle Tour A Complete Travel Guide.pdf
Introduction of Secrets of Mount Kailash.pdf

AWS IoT 핸즈온 워크샵 - 실습 6. 긴급 데이터를 Kinesis Streams으로 보내기 (김무현 솔루션즈 아키텍트)

  • 1. For this lab were going to look at a combination of systems to capture different kinds of data streams. We'll start with the usual AWS IoT system using rules to capture our data but during certain events, as determined by our rules we'll activate a Direct-To-Kinesis stream to capture realtime information. Why would you ever do this? AWS IoT has limits in place for the size of each message but also the number of transactions per second. When streaming realtime telemetry information, if you find you need more than 50TPS you would want to consider going to directly to Kinesis. Let's setup a Kinesis Shard. Let's setup a single shard to capture our stream when it is activated. Open the Kinesis dashboard and pick Kinesis Streams. Click Create Stream. Let's call this "iotshard", you'll enter just 1 shard. Lab 9 - Switch to Kinesis during critical events Step 1
  • 2. We're going to setup some Lambda functions to handle logging for us so we can keep track of our "thing". Open the Lambda dashboard. Click Create a lambda function. You can use the hello-world blue print. Let's call this function, "iotLambda2", accept the basics. You can also enter the code below to turn on some basic logging. Step 2
  • 3. Note: We are not creating these function in a VPC for this lab. Next we need to create another Lambda function to capture our Kinesis stream data. While in the Lambda dashboard, create a new function. Use the Kinesis-Process-Record blue print. Select the Kinesis Stream you created in step 1. Leave the other options as their defaults. We are going to call this iotLambda3. Make sure your role is a Kinesis Role. On the review screen, make sure you pick "Enable Now" so the event source is active.
  • 4. Here is the code if you want to copy & paste: console.log('Loading function'); exports.handler = function(event, context) { console.log('IoT Kinesis Event:', JSON.stringify(event, null, 2)); event.Records.forEach(function(record) { // Kinesis data is base64 encoded so decode here var payload = new Buffer(record.kinesis.data, 'base64').toString('ascii'); console.log('Decoded payload:', payload); }); context.succeed("Successfully processed " + event.Records.length + " records."); }; Lastly we need a Lambda function that can publish a change to our shadow state to turn on Kinesis for our "thing". Create another new Lambda function, use the hello-world blue print. We will call this iotShadowUpdate. The code for this is shown below. JavaScript
  • 5. You will need to pick an execution role that has access to the IoT service. Shadow Update Lambda code is as follows:
  • 6. var aws = require('aws-sdk'); var iotdata = new aws.IotData({endpoint: 'A3V8IRCN9H4H5T.iot.us-west-2.amazonaws.com'}); exports.handler = function(event, context) { console.log("Event to trigger Kinesis: " + JSON.stringify(event)); var shadow = { "state" : { "desired" : { "streamState": "on" } } }; var params = { topic: '$aws/things/thingtest/shadow/update', payload: JSON.stringify(shadow), qos: 0 }; iotdata.publish(params, function(err, data){ if(err){ console.log(err); context.fail(err); } else{ console.log("Shadow Updated"); context.succeed(true); } }); }; We're now going to setup a couple rules. The first rule will be to track critical data points to our Lambda function. The second rule will activate if values are outside the norm and will trigger a shadow state update to our "thing" which tells it to turn on the Kinesis stream. This is done by calling our iotShadowUpdate lambda function. For this lab we're be using 2 new topics. Step 3 JavaScript
  • 7. Open the AWS IoT Dashboard. Click create resource and pick a new rule. Let's call this iotCritical. We'll select * from our iotCritical topic. Pick the default action as Lambda. Pick iotLambda2 that we created earlier. Let's now create the Kinesis rule. Click create resource and pick a new rule again. Let's call this iotKinesis. We'll select * again from our iotCritical topic. We want to add a condition this time, temperature > 100. Pick the default action as Lambda. Pick the iotShadowUpdate we created earlier. Step 4
  • 8. Our script will now connect and send regular AWS IoT messages but one of these will be a high temperature value that will trigger our state change, once we detect the change we'll stream to Kinesis. Let's create a new script for this lab. We'll call this "iotCritical.js". This script is going to be using the full AWS SDK. If you don't have that installed you can run npm install aws-sdk We are also using a sleep library to run this script a little slower: npm install sleep First, create your bootstrap connection code as follows: note: You'll need to add your Kinesis stream endpoint. Step 5 Bash Bash
  • 9. var awsIot = require('aws-iot-device-sdk'); var aws = require('aws-sdk'); var sleep = require('sleep'); var device = awsIot.device({ "host": "data.iot.us-west-2.amazonaws.com", "port": 8883, "clientId": "1234", "thingName": "thingtest", "caPath": "./root-CA.cer", "certPath": "./certificate.pem.crt", "keyPath": "./private.pem.key", "region": "us-west-2" }); var kinesis = new aws.Kinesis({ acessKeyId: "{ACCESS KEY}", secretAccessKey: "{SECRET KEY}", var streamState = "off"; var x = 0; // general purpose timers var t = 1; // master kinesis timer Next on startup we want to set our current shadow state so that our stream is considered off. Let's define our shadow state. var msg = { "state": { "reported": { "streamState": "off" }, "desired": { "streamState": "off" } } } We also want to have some objects ready to modify as we run our test loops: JavaScript JavaScript
  • 10. var normalMsg = { "temperature": 0, "seq": 0 }; var kinesisMsg = { "x": 0, "y": 0, "z": 0, "id": 0 } Next we're going to add the function to handle our shadow changes, when we see a delta and it contains the "on" state we will trigger our Kinesis stream. device.on('message', function(topic, message) { console.log('message', topic, message.toString()); if (topic == "$aws/things/thingtest/shadow/update/delta") { var shadow = JSON.parse(message); streamState = shadow.state.streamState; // report back our state change msg.state.reported.streamState = streamState; device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg)); if (streamState == 'on') { //startStream(); setTimeout(function() { stream(); }, 2500); } } // Start our main loop if (topic == '$aws/things/thingtest/shadow/update/accepted') { // Let's loop slowly with regular messages normalMsg.temperature = 75; normalMsg.seq = x; device.publish('iotCritical', JSON.stringify(normalMsg)); console.log("Our current stream state is " + streamState); console.log("Sent regular message " + x + " at temp: " + normalMsg.temperature ) sleep.sleep(1); // seconds } if (topic == 'iotCritical') { JavaScript JavaScript
  • 11. if (x<100) { x++; normalMsg.temperature = 75; normalMsg.seq = x; // on our 10th message we'll pass the threshold just once and see if our if (x==10) normalMsg.temperature = 110; setTimeout(function() { device.publish('iotCritical', JSON.stringify(normalMsg)); }, 500); console.log("Our current stream state is " + streamState); console.log("Sent regular message " + x + " at temp: " + normalMsg.tempe //sleep.sleep(1); // seconds } else { console.log('Done!'); } } }); The above is pretty simple. We're first checking our streaming state and after that we're using the callback functionailty to trigger a slower loop to keep sending messages to AWS IoT. Once the critical temp is sent (see the line setting our high temp on the 10th message) we see the shadow change to turn on our Kinesis stream. Let's now add the stream() function which just blasts data to Kinesis:
  • 12. var stream = function() { console.log('Starting Kinesis Stream ...'); for(t=1;t<50;t++) { // Let's publish our telemtry data kinesisMsg.id = t; kinesisMsg.x = t; kinesisMsg.y = Math.random() * (5000 - 1) + 1; kinesisMsg.z = kinesisMsg.y/t; kinesis.putRecord({ StreamName : "iotshard", Data : JSON.stringify(kinesisMsg), PartitionKey : "id" }, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred } else { console.log("Sent stream message to Kinesis: " + JSON.string } }); } } Finally we setup our gateway device object as usual and subscribe to the relevant topics: device.on('connect', function() { console.log('Connected!'); setTimeout(function() { device.subscribe('$aws/things/thingtest/shadow/update/delta'); device.subscribe('$aws/things/thingtest/shadow/update/accepted'); device.subscribe('iotCritical'); device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg)); console.log("Set our thing shadow."); console.log('Waiting ...'); }, 2500); }); FULL SOURCE // Lab 9 // Watch our shadow state for kinesis triggers. JavaScript JavaScript JavaScript
  • 13. var awsIot = require('aws-iot-device-sdk'); var aws = require('aws-sdk'); var sleep = require('sleep'); var device = awsIot.device({ "host": "data.iot.us-west-2.amazonaws.com", "port": 8883, "clientId": "1234", "thingName": "thingtest", "caPath": "./root-CA.cer", "certPath": "./certificate.pem.crt", "keyPath": "./private.pem.key", "region": "us-west-2" }); var kinesis = new aws.Kinesis({ acessKeyId: "{Your Access Key}", secretAccessKey: "{Your Sec var streamState = "off"; var x = 0; var t = 1; var msg = { "state": { "reported": { "streamState": "off" }, "desired": { "streamState": "off" } } } var normalMsg = { "temperature": 0, "seq": 0 }; var kinesisMsg = { "x": 0, "y": 0, "z": 0, "id": 0 }
  • 14. device.on('message', function(topic, message) { console.log('message', topic, message.toString()); if (topic == "$aws/things/thingtest/shadow/update/delta") { var shadow = JSON.parse(message); streamState = shadow.state.streamState; // report back our state change msg.state.reported.streamState = streamState; device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg)); if (streamState == 'on') { //startStream(); setTimeout(function() { stream(); }, 2500); } } // Start our main loop if (topic == '$aws/things/thingtest/shadow/update/accepted') { // Let's loop slowly with regular messages normalMsg.temperature = 75; normalMsg.seq = x; device.publish('iotCritical', JSON.stringify(normalMsg)); console.log("Our current stream state is " + streamState); console.log("Sent regular message " + x + " at temp: " + normalMsg.temperature ) sleep.sleep(1); // seconds } if (topic == 'iotCritical') { if (x<100) { x++; normalMsg.temperature = 75; normalMsg.seq = x; // on our 25th message we'll pass the threshold just once and see if our if (x==10) normalMsg.temperature = 110; setTimeout(function() { device.publish('iotCritical', JSON.stringify(normalMsg)); }, 500); console.log("Our current stream state is " + streamState); console.log("Sent regular message " + x + " at temp: " + normalMsg.tempe //sleep.sleep(1); // seconds } else { //process.exit(); console.log('Done!');
  • 15. } } }); var stream = function() { console.log('Starting Kinesis Stream ...'); for(t=1;t<50;t++) { // Let's publish our telemtry data kinesisMsg.id = t; kinesisMsg.x = t; kinesisMsg.y = Math.random() * (5000 - 1) + 1; kinesisMsg.z = kinesisMsg.y/t; kinesis.putRecord({ StreamName : "iotshard", Data : JSON.stringify(kinesisMsg), PartitionKey : "id" }, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred } else { console.log("Sent stream message to Kinesis: " + JSON.string } }); } } device.on('connect', function() { console.log('Connected!'); setTimeout(function() { device.subscribe('$aws/things/thingtest/shadow/update/delta'); device.subscribe('$aws/things/thingtest/shadow/update/accepted'); device.subscribe('iotCritical'); device.publish('$aws/things/thingtest/shadow/update', JSON.stringify(msg)); console.log("Set our thing shadow."); console.log('Waiting ...'); }, 2500); }); You can run this now and you see the switch between AWS IoT and Kinesis. node iotCritical.js Bash