AWS IoT introduction

46
AWS IoT 介介 & 介介介介 Roger
  • Upload

    -
  • Category

    Software

  • view

    755
  • download

    2

Transcript of AWS IoT introduction

Page 1: AWS IoT introduction

AWS IoT 介紹 & 基本用法Roger

Page 2: AWS IoT introduction

1.Main function

Page 3: AWS IoT introduction

Device gatewayAWS IoT 裝置閘道讓裝置能安全並有效地與 AWS IoT 通訊。裝置閘道可以使用 MQTT 來交換訊息,以進行一對一和一對多通訊。

Page 4: AWS IoT introduction

Rule Engine規則引擎會根據定義的規則,評估發佈到 AWS IoT 的訊息,並將訊息轉換並傳輸到其他裝置或雲端服務。規則可套用到來自一或多個裝置的資料,而且可以平行執行一或多個動作。

Page 5: AWS IoT introduction

Rule Action規則引擎也可以將訊息路由到 AWS 終端節點,包括 AWS

Lambda 、 Amazon Kinesis 、 Amazon S3 、 Amazon Machine Learning 和 Amazon DynamoDB

Page 6: AWS IoT introduction

device shadowAWS IoT 為每個裝置建立「陰影」,其中包含裝置的最新狀態,可讓應用程式或其他裝置讀取訊息並與裝置互動。使用裝置陰影即使裝置離線,也能保留每個裝置的上次報告狀態及所需的未來狀態。

Page 7: AWS IoT introduction

Build solutionsAWS IoT 可以透過 app 來控制裝置,但 app 並不是一直和裝置處於連線的狀態,而是透過 REST API 來取得裝置 ( 的影子 ) 目前的狀態,進而進行操作。

Page 8: AWS IoT introduction

Price

區域定價

按實際用量付費,沒有最低費用。價格是根據發佈到 AWS IoT 的訊息數量 ( 發佈成本 ) ,以及透過 AWS IoT 交付至裝置或應用程式的訊息數量 ( 交付成本 ) 來收費。 不會收取以下 AWS 服務交付的費用: Amazon S3 、 Amazon DynamoDB 、 AWS Lambda 、 Amazon Kinesis 、 Amazon SNS 和 Amazon SQS 。 訊息是由 AWS IoT 處理的一個 512 位元組資料區塊。例如, 900 位元組的承載以兩則訊息計費

範例 1裝置每小時發佈一個 500 位元組的訊息至 AWS IoT ,然後 AWS IoT 將每則訊息交付至 5 個其他裝置。1*24*30*(5 USD/Million msg)+ 1*5*24*30*(5 USD/Million msg)= 每月 0.022 USD

範例 2裝置每分鐘發佈一個 1,024 位元組的訊息至 AWS IoT 。然後 AWS IoT 將每則訊息交付至 Amazon S3 。2*60*24*30*(5 USD/Million msg)+ 0= 每月 0.432 USD

Page 9: AWS IoT introduction

2.Install AWS CLI & Setting

Page 10: AWS IoT introduction

Install AWS CLI

The easiest way to install aws-cli is to use pip :

upgrade to the latest version :$ pip install awscli

$ pip install --upgrade awscli

Page 11: AWS IoT introduction

Setting AWS CLI

get started to run the aws configure command :( 需先在 AWS IAM建立使用者,並取得 access key 和 secret key)$ aws configureAWS Access Key ID: foo

AWS Secret Access Key: bar

Default region name [us-west-2]: us-west-2

Default output format [None]: json

Page 12: AWS IoT introduction

Setting AWS CLI

To use environment variables, do the following :

$ export AWS_ACCESS_KEY_ID=<access_key>$ export AWS_SECRET_ACCESS_KEY=<secret_key>

Page 13: AWS IoT introduction

Setting AWS CLI config file

create a configuration file like this :~/.aws/config

[default]aws_access_key_id=<default access key>aws_secret_access_key=<default secret key># Optional, to define default region for this profile.region=us-west-1

[profile testing]aws_access_key_id=<testing access key>aws_secret_access_key=<testing secret key>region=us-west-2

Page 15: AWS IoT introduction

Thing Operating

List all things : $ aws iot list-things[--next-token <value> ex: ”sadfkjigrfhweuhfhewfdh”]

[--max-results <value> ex: 10 ( value > 0 )]

[--attribute-name <value> ex: “attr1” 測試無法過濾多組條件 ]

[--attribute-value <value> ex: “111” 測試無法過濾多組條件 ]

[--cli-input-json <value> ex: file://檔案路徑,如 file://commands.json]

[--generate-cli-skeleton 用來顯示輸入 JSON 檔的格式 ex: 可為空值則將 json顯示在畫面上,也可將 json

寫進檔案,指令後面加上 > commands.json 即可 ]綠字的兩組參數每個指令都有,使用方法也都一樣,後續不再贅述

Page 16: AWS IoT introduction

Thing Operating

Create Things :

Get thingS DATA :

$ aws iot-data create-thing --thing-name <value>

$ aws iot-data describe-thing --thing-name <value>

Page 17: AWS IoT introduction

Thing Operating

update Things :

delete DATA :

$ aws iot-data update-thing --thing-name <value> --attribute-payload <value>

[--attribute-payload <value> ex: attributes={KeyName1=string,KeyName2=string}]

$ aws iot-data delete-thing --thing-name <value>

Page 19: AWS IoT introduction

Secure Communication

Provision a Certificate :$ aws iot create-keys-and-certificate --set-as-active --certificate-pem-outfile cert.pem --public-key-outfile publicKey.pem --private-key-outfile privateKey.pem

*把 certificateArn 記下來! 或是輸入 aws iot list-certificates來查詢[--set-as-active | --no-set-as-active ex: 是否啟用憑證 ][--certificate-pem-outfile <value> ex: cert檔名 ][--public-key-outfile <value> ex: publicKey檔名 ][--private-key-outfile <value> ex: privateKey檔名 ]

Page 20: AWS IoT introduction

Secure Communication

Creates an AWS IoT policy :$ aws iot create-policy --policy-name <value> --policy-document <file://policy.json>

[policy-document 含空白字元長度不可超過 2048 字元 example: policy.json{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action":["iot:*"], "Resource": ["*"] }]}]

Page 21: AWS IoT introduction

Secure Communication

Attach the policy to your certificate :$ aws iot attach-principal-policy --principal arn:aws:iot:ap-northeast-1:000011112222:cert/773415c2aa56da4e07549cf01e0c3bf8cc6d2fc522388f29bff4bc032bfc4238 --policy-name <value>

* 可輸入 aws iot list-thing-principals --thing-name <value> 來查詢 principal[--principal <value> ex: “certificate-arn” ”或是 cognito-id”]

Page 22: AWS IoT introduction

Secure Communication

Attach your Certificate to Your Device :$ aws iot attach-thing-principal --thing-name <value> --principal arn:aws:iot:ap-northeast-1:000011112222:cert/773415c2aa56da4e07549cf01e0c3bf8cc6d2fc522388f29bff4bc032bfc4238

* 可輸入 aws iot list-thing-principals --thing-name <value> 來查詢 principal

Page 24: AWS IoT introduction

Create IAM Role

Create an IAM Role for AWS IoT :$ aws iam create-role --role-name <value> --assume-role-policy-document <file://document.json>example: document.json{ "Version": "2012-10-17", "Statement": [{ "Sid": "", "Effect": "Allow", "Principal": { "Service": "iot.amazonaws.com" }, "Action": "sts:AssumeRole" }]}}}

Page 25: AWS IoT introduction

Create IAM Role

Create IAM policy :$ aws iam create-policy --policy-name <value> --policy-document <file://document.json>

*把 Arn 記下來! 或是輸入 aws iam list-roles來查詢IAM Policy example: document.json Action則依照需求調整{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "dynamodb:*", "lambda:InvokeFunction", "iot:Publish"], "Resource": ["*"] }]}}

Page 26: AWS IoT introduction

Create IAM Role

Attach IAM policy :

adding Other aws service IAM ROLE : 參考連結

$ aws iam attach-role-policy --role-name <value> --policy-arn arn:aws:iam::964391593426:role/iot-actions-role

* 可輸入 aws iam list-roles來查詢各個 Role的 Arn}

Page 28: AWS IoT introduction

Rule Engine

Create a Rule :$ aws iot create-topic-rule --rule-name <value> --topic-rule-payload <file://document.json>Republish example: document.json{ "sql": "SELECT * FROM ‘iot/test’", "ruleDisabled": false, "actions": [{ "republish": { "topic": "another/topic", "roleArn": "arn:aws:iam::964391593426:role/iot-actions-role" } }]}

Page 29: AWS IoT introduction

Rule Engine

Viewing Rules :

Deleting a Rule :

AWS IoT SQL Reference :其他SQL指令用法如select, from, where或是function()

$ aws iot list-topic-rules$ aws iot get-topic-rule --rule-name <value>

$ aws iot delete-topic-rule --rule-name <value>

Page 31: AWS IoT introduction

device shadows flow

Page 32: AWS IoT introduction

device shadowDevice Shadow Document Example : { "state" : { "desired" : { // Applications 將欲更新的狀態寫到 desired ,而不是直接跟 device 連結 "color" : "RED", "sequence" : [ "RED", "GREEN", "BLUE" ] }, "reported" : { // 紀錄裝置 (Device) 當前的狀態, Applications 便可從 reported 取得裝置 (Device) 狀態,而不需直接與裝置(Device) 連結 "color" : "GREEN" } }, "metadata" : { // 用來存放裝置 metadata ,並紀錄資料異動的時間 "desired" : { "color" : { "timestamp" : 1456366063 }, "sequence" : { "timestamp" : 1456366063 } }, "reported" : { "color" : { "timestamp" : 1456366063 } } }, "version" : 10, // 表示 document version ,每次更新 shadow 就 +1 "clientToken" : "UniqueClientToken", // 一串 unique string ,用來確認 MQTT req/res 是否有相關 "timestamp": 1456366063 // 表示訊息在什麼時間點透過 AWS IoT 傳送}

Page 34: AWS IoT introduction

device shadow

/update : $aws/things/thingName/shadow/updatepublish 到該 topic ,用來更新 thing shadow ,並且 response 回 /update/accepted 或 /update/rejected$ aws iot-data publish --topic “$aws/things/thingName/shadow/update” --payload {'a':123,'b':'bbb'}(也可使用 file://path-to-file)

Example PolicyThe following is an example policy:{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["iot:Publish"], "Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update"] }]}

Page 35: AWS IoT introduction

device shadow/update/accepted : $aws/things/thingName/shadow/update/Accepted當 AWS IoT 接收到 /update 且更新成功便會 publish 到 /update/accepted可利用 MQTT.fx 軟體或是 aws iot platform 提供的 MQTT Client 來測試

Example PolicyThe following is an example policy:{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["iot:Subscribe"], "Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update/accepted"] }]}

Page 36: AWS IoT introduction

device shadow/update/rejected : $aws/things/thingName/shadow/update/rejected當 AWS IoT 接收到 /update 且更新失敗便會 publish 到 /update/rejected可利用 MQTT.fx 軟體或是 aws iot platform 提供的 MQTT Client 來測試

其他功能如 get, delete 請參閱文件

Example PolicyThe following is an example policy:{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["iot:Subscribe"], "Resource": ["arn:aws:iot:region:account:topic/$aws/things/thingName/shadow/update/rejected"] }]}

Page 37: AWS IoT introduction

device shadow DEMO 模擬裝置 Update "reported”

$ aws iot-data update-thing-shadow --thing-name <value> --payload '{"state": {"reported" : {"power" : "on"}}}' outfile.json

模擬手機 App Update "desired”$ aws iot-data update-thing-shadow --thing-name <value> --payload '{"state": {"desired" : {"power" : "off"}}}' outfile2.json

模擬取得 Shadow Thing "delta”$ aws iot-data get-thing-shadow --thing-name <value> outfile3.json

”可取得 delta” ”區塊的資料,表示 reported” ”和 desired”資料不同步 模擬同步 Shadow Thing "delta”

$ aws iot-data update-thing-shadow --thing-name <value> --payload '{"state": {"reported" : {"power" : "on"}}}' outfile4.json

模擬再次取得 Shadow Thing "delta”$ aws iot-data get-thing-shadow --thing-name <value> outfile5.json

”可發現 reported” ”和 desired”區塊的資料已同步完成 模擬 Version conflict

$ aws iot-data update-thing-shadow --thing-name <value> --payload '{"state": {"reported" : {"power" : "on"}}, “version” : 1}' outfile6.json

會出現錯誤訊息 A client error (ConflictException) occurred when calling the UpdateThingShadow operation: Version conflict

Page 39: AWS IoT introduction

aws iot sdk for node.jsThe aws-iot-device-sdk.js package allows developers to write JavaScript applications which access the AWS IoT Platform.

API DocumentawsIot.device()

awsIot.thingShadow()

awsIot.thingShadow#register()

awsIot.thingShadow#unregister()

awsIot.thingShadow#update()

awsIot.thingShadow#get()

awsIot.thingShadow#delete()

awsIot.thingShadow#publish()

awsIot.thingShadow#subscribe()

awsIot.thingShadow#unsubscribe()

awsIot.thingShadow#end()

Page 40: AWS IoT introduction

aws iot sdk for node.jsDEVICE CLASS

var awsIot = require('aws-iot-device-sdk');var device = awsIot.device({ keyPath: '~/awsCerts/private.pem.key', certPath: '~/awsCerts/certificate.pem.crt', caPath: '~/awsCerts/root-CA.crt', clientId: 'myAwsClientId', region: 'us-east-1'});device .on('connect', function() { console.log('connect'); device.subscribe('topic_1'); device.publish('topic_2', JSON.stringify({ test_data: 1})); });device .on('message', function(topic, payload) { console.log('message', topic, payload.toString()); });

Page 41: AWS IoT introduction

DEMO!

Page 42: AWS IoT introduction

9.AWS IoT TroubleShooting

Page 43: AWS IoT introduction

AWS IoT TroubleShooting建立 AWS CloudWatch 來查看 AWS IoT Logging Create an IAM Role for AWS IoT :$ aws iam create-role --role-name <value> --assume-role-policy-document <file://document.json>

Logging Role Policy example: document.json{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "iot.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}

Page 44: AWS IoT introduction

AWS IoT TroubleShootingCreate IAM policy & Attach :

Register the Logging Role with AWS IoT :

該步驟可省略, IAM 已經有內建的 CloudWatch 相關的 Policy 可直接使用,透過指令來查詢有哪些可用的Policy$ aws iam list-policies | grep CloudWatch

再把查詢到的 CloudWatch 的 ARN attach 到 role-policy$ aws iam attach-role-policy --role-name <value> --policy-arn arn:aws:iam::964391593426:role/iot-actions-role

$ aws iot set-logging-options --logging-options-payload roleArn="arn:aws:iam::<your-aws-account-num>:role/IoTLoggingRole",logLevel="INFO"

更多關於 AWS CloudWatch 的設定請參閱以下連結:http://docs.aws.amazon.com/zh_cn/iot/latest/developerguide/cloud-watch-logs.html

Page 45: AWS IoT introduction

AWS IoT TroubleShootingLimit :

Topic length limit 256 bytes encoded in UTF-8.

Restricted topic prefix Topics ’開頭 $’ 是保留字,除了 Thing Shadows 外都不可使用Maximum number of slashes in topic and topic filter 最多 8 個 slashes (/)

Client ID size limit 128 bytes encoded in UTF-8.

Restricted client ID prefix ’$’ 是 client IDs 保留字Message size limit payload 最多 128 KB ,若超過大小會被 AWS IoT

Service reject

Page 46: AWS IoT introduction

thanks!Any [email protected]