Louie NRT Story

[AWS] IoT Core -> Lambda -> DynamoDB (2) 본문

서버시스템

[AWS] IoT Core -> Lambda -> DynamoDB (2)

hyeok0724.kim@gmail.com 2020. 2. 4. 20:23
반응형

Writed: 4 FEB 2020

 

Index

1. Create Table

2. Create a Rule with a AWS Lambda Action

3. Runing Lambda

 

1. Create Table

1) Choose create table

2) Enter name and Primary key

 - DynamoDB is a schema-less database that only requires a table name and primary key.

 - The table's primary key is made up of one or two attributes that uniquely identify items, partition the data, and sort data within each partition.

3) Create item

 

2. Create a Rule with a AWS Lambda Action

1) Choose Create an AWS IoT Rule

2) Enter a name for your rule and input the query in Rule query statement

3) Choose Add action and Create new Lambda Function

 - Grant DynamoDB permission to new policy

4) Choose Create rule

3. Runing Lambda

1) Check Lambda's Trigger

2) Enter Code

from __future__ import print_function
  
import json
import boto3
  
print('Loading function')

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if abs(o) % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)
  
def lambda_handler(event, context):
  
    # Parse the JSON message 
    eventText = json.dumps(event)
    
    dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-2')
    
    table = dynamodb.Table('eccTest03_TB')
    
    date = '2020-02-02 00:00:01'
    targetPower = int(event['targetPower'])
    currentPower = int(event['currentPower'])
    
    response = table.put_item(
        Item={
           'Date' : date,
           'targetPower': targetPower,
           'currentPower': currentPower
       }
    )
    
    # Print the parsed JSON message to the console. You can view this text in the Monitoring tab in the AWS Lambda console or in the Amazon CloudWatch Logs console.
    print('Received event: ', eventText)
    print("PutItem succeeded:")
    print(json.dumps(response, indent=4, cls=DecimalEncoder))

3) Test Lambda

4) Check Data inserted in DynamoDB

 

Reference

https://docs.aws.amazon.com/

 

https://docs.aws.amazon.com/

 

docs.aws.amazon.com

 

반응형

'서버시스템' 카테고리의 다른 글

[AWS] Summit 2021 - Todo  (0) 2021.05.12
[Windonws] 원격데스크톱 포트 변경 방법  (0) 2020.03.03
[AWS] IoT Core -> Lambda -> DynamoDB (1)  (0) 2020.01.27
[AWS] API Gateway -> Lambda  (0) 2020.01.27
[AWS] IOT Core Lambda  (0) 2020.01.13
Comments