AWS IoT

(株)HIRO ICT 研究所の「空間知能化システム」で使用するAWS IoTをご紹介します。

AWS IoTとは

AWS IoTの仕組み

AWS IoT では、接続されたデバイスが簡単かつ安全にクラウドアプリケーションやその他のデバイスとやり取りできるマネージド型クラウドプラットフォームです。

AWS IoT では数十億のデバイスと数兆のメッセージをサポートし、それらのメッセージを AWS エンドポイントおよび他のデバイスに確実かつ安全に処理しルーティングします。

AWS IoT によってアプリケーションはそれらが接続されていない場合でも、全てのデバイスを常に追跡し通信することができます。

AWS IoT を使用すると AWS Lambda、Amazon Kinesis、Amazon S3、Amazon Machine Learning、Amazon DynamoDB など AWS の各種サービスが簡単に使用でき、 接続されたデバイスによって生成されたデータをインフラストラクチャの管理を必要とせずに収集、処理、分析、実行する IoT アプリケーションを構築できます。

デバイスを接続し管理する

AWS IoT ではデバイスをクラウドや他のデバイスに簡単に接続できます。

AWS IoT では、断続的な接続を許容し、デバイスのコードフットプリントを削減し、 必要なネットワーク帯域幅を削減するよう特にデザインされた HTTP と MQTT といった軽量の通信プロトコルをサポートしています。

AWS IoT では他の業界標準およびカスタムプロトコルをサポートし、複数の異なるプロトコルを使用しているデバイス同士でも相互に通信できます。


IoT デバイスの接続

安全なデバイスの接続とデータ

AWS IoT では接続するすべてのポイントで認証とエンドツーエンドの暗号化を提供し、デバイスと AWS IoT 間で身元が証明されたデータのみが交換されます。

それに加え、詳細なアクセス権限のポリシーを適用することによってデバイスとアプリケーションに安全にアクセスできます。


安全な IoT デバイスの接続

デバイスデータに対する処理と活用

定義したビジネスルールに基づいて AWS IoT でデバイスデータを迅速にフィルタリング、変換、活用できます。

いつでもアプリケーションの機能を新しいデバイスに実装し、ルールをアップデートできます。

AWS IoT は AWS Lambda、Amazon Kinesis、Amazon S3、Amazon Machine Learning、Amazon DynamoDB など AWS の各種サービスを、 さらに強力な IoT アプリケーションのために簡単に使用できます。


IoT データを処理する

デバイスの状態の読み込み設定をいつでも

AWS IoT ではデバイスの最新の状態情報を保存し、いつでも読み込みまたは設定できるので、デバイスが常にオンラインであるかのようにアプリケーションに出現させることができます。

これはデバイスとの通信が切断されていてもアプリケーションがデバイスの状態を読み込むことができ、 デバイスが再接続された時にもデバイスの状態を設定し実装できることを意味します。


永続的な IoT デバイスの接続

AWS IoTの特徴

AWS IoT によって、さまざまなデバイスを AWS の各種 Services や他のデバイスに接続し、データと通信を保護し、 デバイスデータに対する処理やアクションを実行することが可能になります。

アプリケーションからは、デバイスがオフラインの状態でもデバイスとのやり取りが可能です。

AWS IoT デバイス SDK

AWS IoT には、ハードウェアデバイスやモバイルアプリケーションを簡単に、すばやく接続できるようサポートする SDK が準備されています。

AWS IoT デバイス SDK を使用すれば、AWS IoT との間で MQTT または HTTP プロトコルを介した接続、認証、メッセージ交換が可能になります。

このデバイス SDK では C、JavaScript および Arduino がサポートされており、クライアントライブラリ、開発者ガイドおよびメーカー向けの移植ガイドが付属しています。

オープンソースの SDK を使用することや、独自に SDK を作成することも可能です。

詳細については、AWS IoT Device SDK documentation をお読みください。SDK をダウンロードしてすぐに開始することもできます。

デバイスゲートウェイ

AWS IoT のデバイスゲートウェイによって、デバイスと AWS IoT との間の安全かつ効率的な通信が可能になります。

デバイスゲートウェイでは、公開モデルまたはサブスクリプションモデルによってメッセージをやり取りすることができ、1 対 1 および 1 対多の通信が可能です。

AWS IoT ではこの 1 対多の通信パターンによって、接続された 1 つのデバイスから、指定されたトピックについて複数の受信者にデータをブロードキャストできます。

デバイスゲートウェイでは MQTT および HTTP 1.1 プロトコルがサポートされており、専用プロトコルやレガシープロトコルのサポート実装も容易に行えます。

デバイスゲートウェイは、インフラストラクチャのプロビジョニングが不要でありながら、10 億台以上のデバイスにも対応できるよう自動的にスケールされます。

詳細については、AWS IoT ユーザーガイドの「Protocols」を参照してください。

認証と認可

AWS IoT では、接続するすべてのポイントでの相互認証と暗号化が提供されており、デバイスと AWS IoT 間では身元が証明されたデータのみが交換されます。

AWS IoT では、AWS の認証メソッド (「SigV4」と呼ばれます) および X.509 証明書ベースの認証がサポートされています。

HTTP を使用した接続ではどちらのメソッドも使用できますが、MQTT を使用した場合は証明書ベースの認証を使用します。

それぞれの証明書に対するロールやポリシーの選択をマッピングでき、デバイスに触れることなく、デバイスやアプリケーションによるアクセスを認証したり、 考えが変わったときにすべてのアクセスを取り消したりできます。

デバイスについての証明書やポリシーの作成、デプロイおよび管理は、コンソールから、または API を使用して実行できます。

これらのデバイス証明書のプロビジョニング、アクティベーションおよび関連付けは、AWS IAM を使用して設定された関連ポリシーによって行えます。

これにより、必要な場合にはいつでも個別のデバイスのアクセスを即座に取り消すことができます。

AWS IoT では、ユーザーのモバイルアプリケーションからの接続も Amazon Cognito によってサポートしています。

アプリケーションのユーザーに一意の ID を作成し、権限が限定された一時的な AWS 認証情報を取得するために必要なすべての手順は Amazon Cognito によって処理されます。

詳細については、AWS IoT ユーザーガイドの「Security and Authentication」セクションを参照してください。

レジストリ

レジストリによって、デバイスの ID が確定され、デバイスの属性や機能といったメタデータが追跡されます。 各デバイスには、デバイスのタイプや接続方法にかかわらず、一貫した形式の一意の ID がレジストリによって割り当てられます。

センサーが温度を報告するかどうか、および温度データが華氏か摂氏かといった、デバイスの機能を説明するメタデータもサポートされています。

レジストリではデバイスについてのメタデータを追加料金なしで保存でき、最低 7 年間に 1 度レジストリのエントリを更新していれば、 レジストリ内のメタデータが期限切れになることはありません。

詳細については、AWS IoT ユーザーガイドの「Registry」セクションを参照してください。

デバイスのシャドウ

AWS IoT では、それぞれのデバイスについて「シャドウ」、つまり永続的な仮想バージョンを作成できます。

シャドウにはデバイスの最新の状態が保存されるため、アプリケーションや他のデバイスからのメッセージの読み出し、およびデバイスとの通信が実行できます。

デバイスのシャドウには、デバイスがオフライン状態のときでも、各デバイスについて最後に報告された状態と、希望する今後の状態が保持されます。

最後に報告された時点の状態の取得や、希望する今後の状態の設定は、API またはルールエンジンによって実行できます。

デバイスのシャドウでは、REST API が常時利用できるため、デバイスと協働するアプリケーションの構築が容易になります。

さらに、アプリケーションではデバイスの現在の状態を取得することなく、希望する今後の状態を設定できます。

希望する状態と最後に報告された時点の状態との相違は AWS IoT によって比較され、相違を補うようデバイスに対してコマンドが送られます。

AWS IoT デバイス SDK によって、簡単にデバイスの実際の状態とシャドウを同期させ、シャドウによって設定された希望する今後の状態に対応させることができます。

デバイスのシャドウには、デバイスの状態を最大 1 年間無料で保存できます。最低 1 年間に 1 度更新していれば、デバイスのシャドウは無期限に継続できます。 更新しなかった場合は消去されます。

詳細については、AWS IoT ユーザーガイドの Device Shadows セクションを参照してください。

ルールエンジン

ルールエンジンによって、インフラストラクチャの管理を一切必要とせずに、接続されたデバイスによって生成されるデータを収集し、処理し、分析し、 データに基づいたアクションを実行するアプリケーションを構築することが可能になります。

ルールエンジンでは、お客様が定義したビジネスルールに基づいて、AWS IoT に向けて発行された入力メッセージが評価、変換され、 別のデバイスやクラウドサービスへと配信されます。

1 つのデバイスからのデータにも、多数のデバイスからのデータにも同じルールを適用でき、アクションを単独で実行することも、 多数のアクションを並行して実行することも可能です。

ルールエンジンによって、AWS Lambda、Amazon Kinesis、Amazon S3、Amazon Machine Learning および Amazon DynamoDB などの AWS エンドポイントへのメッセージのルーティングも行えます。

AWS Lambda、Amazon Kinesis および Amazon Simple Notification Service (SNS) を使用して外部のエンドポイントに届けることも可能です。

ルールは、マネジメントコンソール内で作成するか、または SQL に似た構文を使用して作成します。

メッセージの内容に応じて異なる動作をするようにルールを作成できます。

例えば、温度の読み取り値が一定のしきい値を越えたときに、AWS Lambda にデータを送信するルールをトリガーするようにします。

他のデバイスからのデータなど、クラウド内の他のデータを組み合わせるようにルールを作成することも可能です。

例えば、温度が他の 5 つのデバイスの平均より 15% 以上高かった場合にアクションを実行するよう設定できます。

ルールエンジンにはデータの変換に使用可能な数十の機能が準備されており、AWS Lambda を介することで無限に増やすことが可能です。

例えば、広い範囲の値を扱っている場合、入力される数値の平均を取ることができます。

ルールからは、AWS Lambda 内の Java、Node.js または Python コードをトリガーすることも可能なので、最大限の柔軟性と能力を備えたデバイスデータ処理が行えます。

詳細については、AWS IoT ユーザーガイドの Rules セクションを参照してください。

AWS IoTの関連リンク

MQTTとは何か

MQTTは1999年にIBM社とEurotech社のメンバーにより考案されたプロトコルで、2014年8月現在における最新のバージョンはMQTT3.1.1である。 現在、コンピュータと通信に関する標準化団体であるOASISによって、MQTTの標準化が進められている。

MQTTの特徴

MQTTとは、M2MやIoTの実現に適したシンプルで軽量なプロトコル

MQTTはM2M (Machine-to-Machine)、すなわち機械と機械が通信ネットワークを介してお互いに情報をやり取りすることや、 IoT (Internet of Things)、すなわち家電や自動車など多種多様な「モノ」がインターネットにつながり、お互いに情報をやり取りすることを実現するのに適したプロトコルである。

MQTTでは、あらゆる「マシン」や「モノ」に取り付けた、低帯域でメモリー容量の小さなセンサーやデバイスなどから情報を送ることを想定している。

MQTTは、一方向、1対1の通信のみでなく、双方向、1対多の通信が可能である。

また、MQTTのプロトコルヘッダーは最小2バイトと小さく、その軽量さから、特にバッテリーの消費を抑えたいモバイル向けの通信に適していることが特長の一つである。

また同期処理が必要となるHTTPと比較して、処理速度に優れており、とくにリアルタイムでのプッシュ型のメッセージ配信においては、転送量を効果的に低く抑えることができる。

MQTTは、TCP/IPプロトコルの上で動作する、パブリッシュ/サブスクライブ型のモデルを採用

パブリッシュ/サブスクライブ型のモデルでは、メッセージを送信する側をパブリッシャー、メッセージを受信する側をサブスクライバーと言う。

実際にMQTTを利用してメッセージのやり取りを行うには、パブリッシャーとサブスクライバーとの間に、メッセージを仲介するMQTTサーバーを用意する必要がある。

パブリッシャーは、サブスクライバーを意識することなく、サーバーにメッセージの送信ができる一方で、 サーバーは、それらのメッセージを一旦預かり、管理し、適切にサブスクライバーに配信する責任を持つ。

パブリッシャーはトピックを指定してサーバーにメッセージを送信し、送信されたメッセージは、サーバーによってそのトピックに対してサブスクライブを申し込んでいたサブスクライバーに配信される。

  • パブリッシャーとサブスクライバーの間にはMQTTサーバーが存在し、メッセージの管理、配信を行う
  • パブリッシャーはトピックを指定して、メッセージをMQTTサーバに送信する
  • MQTTサーバは、サブスクライバーが指定しているトピックに該当するメッセージを配信する

※ トピックはパブリッシュされたメッセージをどのサブスクライバーが受信するべきかを決定するために使用される

MQTTの機能

トピック

サブスクライバーは、指定するトピックだけサブスクライブすることが出来る。

たとえば、あるデータセンターの温度と湿度についての情報を受信することを想定してみる。

/datacenter/abc/tokyo/floor/01/temperature
/datacenter/abc/tokyo/floor/01/humidity
/datacenter/abc/osaka/floor/01/temperature
/datacenter/abc/osaka/floor/01/humidity
/datacenter/xyz/tokyo/floor/05/temperature
/datacenter/xyz/tokyo/floor/05/humidity
/datacenter/xyz/nagoya/floor/12/temperature
/datacenter/xyz/nagoya/floor/12/humidity

トピックはこのように「/」で区切られた階層構造になっています。

サブスクライバー側では、サブスクライブしたいトピックを指定できます。この時完全一致ではなく、ワイルドカード(Wildcard)も指定できる。

 /datacenter/abc/tokyo/floor/01/temperature

この場合は、完全一致、つまり「ABCデータセンターの、東京拠点にある、1階の温度」に関する情報だけがサブスクライブできる。

 /datacenter/xyz/nagoya/#

「#」を使えば、前方一致という意味になる。つまりこの場合は、「XYZデータセンターの、名古屋拠点にある、すべての階の温度と湿度」に当てはまる情報がサブスクライブできる。

 /datacenter/+/tokyo/floor/+/humidity

「+」を使えば、部分一致という意味になる。つまりこの場合は、「すべてのデータセンターの、東京拠点にある、すべての階の湿度」に当てはまる情報がサブスクライブできる。

「+」は「#」と組み合わせて使用することも可能である。

QoS

MQTTではメッセージごとに到達保証に関するQoS(サービスの品質)が指定でき、以下の3 種類から選択できます。

  • QoS0 : メッセージは最高 1 回 (At most once) 配信されます。
  • メッセージはTCP/IP ネットワークのベストエフォートに従って送信されるため、メッセージが送信先に届くかは保証されません。

  • QoS1 : メッセージは最低 1 回 (At least once) 配信されます。
  • メッセージが送信先に届くことが保証されますが、重複して届く可能性があります。

  • QoS2 : メッセージは正確に 1 回 (Exactly once) 配信されます。
  • メッセージが過不足なく 1 回のみ到着することが保証されます。たとえば、メッセージの重複や損失が許されない課金システムなどで利用できます。

Will

クライアントは最初にMQTTサーバーに接続した時にWillという情報を追加できます。

ここでのWillは「遺言」の意味です。サーバーはそのクライアントとの通信が意図しない理由で切断された場合に、このWillで指定されたトピックとメッセージをサブスクライバ―に送信します。

これにより、サブスクライバー側ではパブリッシュ側が「死んだ」ということを判断できます。

なお、パブリッシュの死活判定は、一定間隔ごとに送られるpingに答えるかどうかで判断されます。

この間隔も接続のたびに決められますので、このデバイスはバッテリーの消費が心配だからping間隔を長くしよう、といった設定ができます。

Retain

Retain機能とは、トピックごとに最後にパブリッシュされたメッセージをMQTTサーバーが保持しておき、新しいサブスクライバーにそのメッセージを渡す機能です。

MQTTは前述のとおり、パブリッシュ/サブスクライブ型モデルです。

そのため、パブリッシュされた時にサブスクライブしていたクライアントにしかメッセージは送信されません。

たとえば1時間ごとに更新される情報を得ようとサブスクライブしても、最長1時間はなにも情報が得られないことになります。

しかし、この場合でもRetain機能を使うとその時点での最新の情報が得られます。

セキュリティ

MQTTは、最初にサーバーに接続するときにユーザー名とパスワードを指定するようにできます。

ただし、パスワード自体はクリアテキストで送られてくるのでTLS (Transport Layer Security) を通してセキュリティを構築することになっています。

また、バージョン 3.1.1 からサブスクライバーを拒否する仕様は存在しますが、どのような理由で拒否するかは仕様では決まっていません。

ただし、現在世の中に出ている一部のMQTTサーバーでは、ユーザー名ごとにパブリッシュ/サブスクライブそれぞれのアクセス管理をできる機能が実装されています。

さきほどユーザー名とパスワードを指定すると書きましたが、この扱いについては実装依存です。通常の認証に加えて、LDAPやOAuthを使って認証をする、という実装も可能です。

AWS IoTを使って見る

やりたいこと

  • Publisher(センサー側)として「BCM94343WWCD1_EVB」を使用する。
  • Suscriber(アクリチュエータ側)として「BCM943364WCD1_EVB」を使用する。
  • Publisher(センサー側)のボタン(SW3)を押すと、AWS IoTにPublishされる。
  • AWS IoTからSuscriber(アクリチュエータ側)に「LED点灯」がSuscribeされる。


やりたいこと

AWS IoTでの設定

thing作成
  • AWS IoTのResources画面から「Create a thing」
  • Name欄にthing名を入れて、Createします(例:wiceddemo)
暗号化キーのダウンロード
  • Resources画面にあるthingをクリック
  • 画面右側の詳細ウィンドウで「Coonect a device」
  • Embedded Cを選択しGenerateボタンを押す
  • 3つの暗号化キーをダウンロードして保管
サーバアドレスの確認
  • Confirn and start connectingボタンを押す
  • 表示されるサンプルコードをコピーして保管(以下に例を示す)
    →後でソースコードに内容を貼り付ける(ファイル名は任意)
AWS IoT C SDK
Download one of the AWS IoT C SDKs:

OpenSSL
mbed-TLS
Set up the SDK using the instructions in our README on GitHub.

Add in the following sample code based on your account, Thing, and new certificate:

// Get from console
// =================================================
#define AWS_IOT_MQTT_HOST              "XXXXXXXXXXX.iot.us-west-2.amazonaws.com"
#define AWS_IOT_MQTT_PORT              8883
#define AWS_IOT_MQTT_CLIENT_ID         "wiceddemo"
#define AWS_IOT_MY_THING_NAME          "wiceddemo"
#define AWS_IOT_ROOT_CA_FILENAME      "root-CA.crt"
#define AWS_IOT_CERTIFICATE_FILENAME   "YYYYYYYYYY-certificate.pem.crt"
#define AWS_IOT_PRIVATE_KEY_FILENAME   "YYYYYYYYYY-private.pem.key"
// =================================================
Start one of the sample applications found in the SDK. You can use the AWS IoT console to observe the state of your thing's shadow and interact with your device by updating the shadow. Only one device can use a clientID for connecting to the AWS IoT platform at the same time. If you want to connect multiple devices concurrently please create a separate thing (and client certificate) per device that you intend to connect.

Return to Thing Detail

WCED SDKでの設定

暗号化キーの設定
  • \resources\apps\aws_iot\にコピー
    ファイル名を以下のように変えて上書きする
    ・certificate.pem→client.cer
    ・private.pem→privkey.cer
MQTT Brokerの設定
  • \apps\aws_iot\demo\pub_sub\
    publisher.cとsubscriber.cの両方を編集する
    ・MQTT_BROKER_ADDRESS:AWS_IOT_MQTT_HOST→上記のサンプルコードからコピペする
    ・WICED_TOPIC→thing名
無線LANの設定
  • \apps\aws_iot\demo\pub_sub\
    wifi_config_dct.hを編集する
    →publisherとsubscriberの両方を編集する
    ・CLEINT_AP_SSID: 指定されたSSID
    ・CLEINT_AP_PASSPHRASE: 指定されたPassphrase

F/Wビルドと動作確認

ビルドの準備
  • WICED IDEのMake Targetウインドウ
    WICED SDKを右クリックして「new」
    Make Targetを2つ作成
    ・demo.aws_iot.pub_sub.publisher-BCM94344WWCD1 download
    ・demo.aws_iot.pub_sub.subscriber-BCM943364WCD1 download
Suscriber側のビルドと書き込み
  • 省略
Publisher側のビルドと書き込み
  • 省略
動作確認
  • 省略

Publisher側のアプリ

Publisher側のアプリの作成方法

To run the app, work through the following steps.

  1. Modify Wi-Fi configuration settings CLIENT_AP_SSID and CLIENT_AP_PASSPHRASE in wifi_config_dct.h to match your router settings.
  2. Update the AWS MQTT broker address (MQTT_BROKER_ADDRESS) if needed.
  3. Make sure AWS Root Certifcate 'resources/apps/aws_iot/rootca.cer' is up to date while building the app.
  4. Copy client certificate and private key for the given AWS IOT user in resources/apps/aws_iot folder.
    Ensure that valid client certificates and private keys are provided for the AWS IOT user in resources/apps/aws_iot folder.
  5. Build and run this application.
  6. Run another application which subscribes to the same topic.
  7. Press button WICED_BUTTON1 to publish the messages "LIGHT ON" or LIGHT OFF" alternatively and check if it reaches subscriber app running on the other WICED board (which can be anywhere but connected to internet)

mqtt_conn_open()

  • Open a connection and wait for MQTT_REQUEST_TIMEOUT period to receive a connection open OK event

mqtt_app_publish()

  • Publish (send) message to WICED_TOPIC and wait for 5 seconds to receive a PUBCOMP (as it is QoS=2).

mqtt_conn_close()

  • Close a connection and wait for 5 seconds to receive a connection close OK event

application_start()

  • このアプリケーションのメインルーテインである。

ADCデータの初期設定例

/*******************************************************************************
* Function Name  : InitADC2
* Description    : Initialize ADC2 as single shot mode
*                  Set PC.4 (Primer2 Extention Connector Pin 11) as analog input
*
*******************************************************************************/
void InitADC2( void )
{
    GPIO_InitTypeDef GPIO_InitStructure;
    ADC_InitTypeDef  ADC_InitStructure;
 
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC2, ENABLE);
 
    GPIO_StructInit (&GPIO_InitStructure);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
 
    /* ADC1 Configuration ------------------------------------------------------*/
    ADC_InitStructure.ADC_Mode                = ADC_Mode_Independent;
    ADC_InitStructure.ADC_ScanConvMode        = DISABLE;
    ADC_InitStructure.ADC_ContinuousConvMode  = DISABLE;
    ADC_InitStructure.ADC_ExternalTrigConv    = ADC_ExternalTrigConv_None;
    ADC_InitStructure.ADC_DataAlign           = ADC_DataAlign_Right;
    ADC_InitStructure.ADC_NbrOfChannel        = 1; 
    ADC_Init( ADC2, &ADC_InitStructure );
 
    /* ADC2 regular channel14 configuration to sample time = 55.5 cycles */
    ADC_RegularChannelConfig( ADC2, ADC_Channel_14, 1, ADC_SampleTime_55Cycles5);
 
    /* Enable ADC2  */
    ADC_Cmd(ADC2, ENABLE);
 
    /* Enable ADC2 reset calibaration register */  
    ADC_ResetCalibration(ADC2);
 
    /* Check the end of ADC1 reset calibration register */
    while(ADC_GetResetCalibrationStatus(ADC2));
 
    /* Start ADC2 calibaration */
    ADC_StartCalibration(ADC2);
    /* Check the end of ADC2 calibration */
    while(ADC_GetCalibrationStatus(ADC2)); 
}

ADCデータの取得例

/*******************************************************************************
* Function Name  : getCxAdc1Value
* Description    : Get ADC converted value of ADC2 ch-14 (CX_ADC1)
*                  Use single conversion mode
* Input          : NONE
* Return         : Converted value
*******************************************************************************/
u16 getCxAdc1Value(void)
{
    // Start ADC2 Software Conversion
    ADC_SoftwareStartConvCmd( ADC2, ENABLE );
    // Wait until conversion completion
    while(ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC) == RESET);
    // Get the conversion value
    return ADC_GetConversionValue(ADC2);
}

Subscriber側のアプリ

Subscriber側のアプリの作成方法

  1. Modify Wi-Fi configuration settings CLIENT_AP_SSID and CLIENT_AP_PASSPHRASE in wifi_config_dct.h to match your router settings.
  2. Update the AWS MQTT broker address (MQTT_BROKER_ADDRESS) if needed.
  3. Make sure AWS Root Certifcate 'resources/apps/aws_iot/rootca.cer' is up to date while building the app.
  4. Copy client certificate and private key for the given AWS IOT user in resources/apps/aws_iot folder.
    Ensure that valid client certificates and private keys are provided for the AWS IOT user in resources/apps/aws_iot folder.
  5. Build and run this application.
  6. Run another application which publishes to the same topic from anywhere but connected to internet.
  7. Publish the messages "LIGHT ON" or LIGHT OFF" alternatively from the publisher app and check if LED1 gets set accordingly.

mqtt_conn_open()

  • Open a connection and wait for MQTT_REQUEST_TIMEOUT period to receive a connection open OK event

mqtt_app_subscribe()

  • Subscribe to WICED_TOPIC and wait for 5 seconds to receive an ACM.

mqtt_conn_close()

  • Close a connection and wait for 5 seconds to receive a connection close OK event

application_start()

  • このアプリケーションのメインルーテインである。

aws_common.c

「aws_common.c」に色々と便利な関数が用意されている

  • 「#include "aws_common.h"」を追加すると、aws_common.cの中の関数を使用できるようになるようだ。 ただし、subscriber用ばかりのようだから、制御機器を接続するデバイス用かも。

wiced_result_t aws_app_init( aws_app_info_t *app_info );

wiced_result_t aws_mqtt_app_publish( wiced_mqtt_object_t mqtt_obj, uint8_t qos, uint8_t *topic, uint8_t *data, uint32_t data_len );

  • Publish (send) WICED_MESSAGE_STR to WICED_TOPIC and wait for 5 seconds to receive a PUBCOMP (as it is QoS=2).

wiced_result_t aws_mqtt_conn_open( wiced_mqtt_object_t mqtt_obj, wiced_mqtt_callback_t callback );

  • Open a connection and wait for MQTT_REQUEST_TIMEOUT period to receive a connection open OK event

wiced_result_t aws_mqtt_conn_close( wiced_mqtt_object_t mqtt_obj );

  • Close a connection and wait for 5 seconds to receive a connection close OK event

wiced_result_t aws_mqtt_app_subscribe( wiced_mqtt_object_t mqtt_obj, char *topic, uint8_t qos );

  • Subscribe to WICED_TOPIC and wait for 5 seconds to receive an ACM.

wiced_result_t aws_mqtt_app_unsubscribe( wiced_mqtt_object_t mqtt_obj, char *topic );

  • Unsubscribe from WICED_TOPIC and wait for 10 seconds to receive an ACM.

wiced_result_t mqtt_connection_event_cb( wiced_mqtt_object_t mqtt_object, wiced_mqtt_event_info_t *event );

AWS IoT側のアプリ

ルール・アクション

DynamoDBアクション

The dynamoDB action allows you to write all or part of an MQTT message to a DynamoDB table.

When creating a DynamoDB rule, you must specify the following information:

  • hashKeyField

    The name of the hash key (also called the partition key).

  • hashKeyValue

    The value of the hash key.

  • rangeKeyField

    The name of the range key (also called the sort key).

  • rangeKeyValue

    The value of the range key.

  • payloadField

    Optional. The name of the field where the payload will be written.

    If this value is omitted, the payload is written to payload field.

  • table

    The name of the DynamoDB table.

  • roleARN

    The IAM role that allows access to the DynamoDB table.

    At a minimum, the role must allow the dynamoDB:PutItem IAM action.

The data written to the DynamoDB table is the result from the SQL statement of the rule.

The hashKeyValue and rangeKeyValue fields are usually composed of expressions (for example, ${topic()}”or “${timestamp()}").

Note

Non-JSON data is written to DynamoDB as binary data.

The DynamoDB console will display the data as base 64 encoded text.

The following JSON example shows how to define a dynamoDB action in an AWS IoT rule:

{
	"rule": {
		"ruleDisabled": false,
		"sql": "SELECT * AS message FROM 'some/topic'",
		"description": "A test Dynamo DB rule",
		"actions": [{
			"dynamoDB": {
				"hashKeyField": "key",
				"roleArn": "arn:aws:iam::123456789012:role/aws_iot_dynamoDB",
				"tableName": "my_ddb_table",
				"hashKeyValue": "${topic()}",
				"rangeKeyValue": "${timestamp()}",
				"rangeKeyField": "timestamp"
			}
		}]
	}
}

For more information about DynamoDB, see the Amazon DynamoDB Getting Started Guide.

農業ハウスの温度制御 - 温度センサー側のアプリ

農業ハウスの温度制御 - 温度センサー側のアプリの概要

This application should be run on the sensors. The sensor used here is Thermistor (temperature sensor).

The app gets outside temperature from openweathermap.org and room temperature from the sensor.

Finds the difference and publishes ON/OFF to the device (thing name) which it wants to control smartly.

This application reads room temperature every 5 seconds and gets outside temperature from www.openweathermap.org.

And publishes "ON" or "OFF" based on the difference in temperature with QOS-1.

If temperature difference is >= 5 degrees it publishes "ON" to the topic configured via Web-Ui else publishes "OFF".

農業ハウスの温度制御 - 温度センサー側のアプリの処理

To demonstrate the app, work through the following steps.

  1. Make sure AWS Root Certifcate 'resources/apps/aws_iot/rootca.cer' is proper while building the app.
  2. Configuring the sensor using Web-UI:
    a) Connect from a PC to the sensor SSID "WICED_AWS" which runs as soft AP. SSID and credentials are as per DCT configuration.
    b) After successful connection, this sensor will act as WebServer with IP address 192.168.0.1.
    c) From host system type URL in browser as 192.168.0.1.
    d) Configure settings for thing name and upload certificate and private key. And join to a router which is connected to internet.
    e) The WICED board (sensor) will now reboot.
  3. The device will connect to selected Wi-Fi configurations. And then connect to broker.
  4. To send "ON" to the device try to make the temperature difference >= 5 degrees else make it < 5.

農業ハウスの温度制御 - 制御装置側のアプリ

農業ハウスの温度制御 - 制御装置側のアプリの概要

This application should run on the device which needs to be controlled using IOT protocols and Cloud.

The device used here is LED1 on the WICED board.

It has 2 states (ON/OFF) which could be controlled using one of the below mentioned topics which the device subscribes:

  • a) Name of this device (thing name). Whoever publishes message to this thing name (device) can control the device.
    This can be treated as SMART CONTROL of the device. This publish message can be triggered from one of the below:
    i) AWS Ice Breaker.
    ii) Other AWS Cloud service like Lambda.
    iii) Directly from remote sensor. We are using this for this demo.
  • b) AWS shadow for this thing name (device). This is used to create a virtual instance of this device in cloud.
    Users can get to know the status of the thing (device) by checking shadow. Also the device can be controlled using Shadow.
    This topic is derived from thing name which needs to be configured as already mentioned in item a) above.
    This can be treated as REMOTE CONTROL of the device.
  • Also the device can be configured to be smart controlled or not using 2 ways:
    i) Press SW3 button to allow/disallow smart control.
    ii) Update "auto" element in "desired" object to "YES" or "NO" in AWS Shadow for the given thing name

The device publishes to shadow when there is any change in its status.

農業ハウスの温度制御 - 制御装置側のアプリの概要

To demonstrate the app, work through the following steps.

  1. Make sure AWS Root Certifcate 'resources/apps/aws_iot/rootca.cer' is proper while building the app.
  2. Configuring the device using Web-UI:
    a) Connect from a PC to the device SSID "WICED_AWS" which runs as soft AP. SSID and credentials are as per DCT configuration.
    b) After successful connection, this device will act as WebServer with IP address 192.168.0.1.
    c) From host system type URL in browser as 192.168.0.1.
    d) Configure settings for thing name and upload certificate and private key. And join to a router which is connected to internet.
    e) The device will now reboot.
  3. The device will connect to selected Wi-Fi configurations. And then connect to broker.
  4. Try to control the device with one of the following:
    a) Start sensor app and try to get ON/OFF published to the device thing name.
    b) Update desired shadow status (ON/OFF) for the device thing name in the AWS IOT service.
    Item a) can be disabled/enabled by toggling the SW3 button on the device or by changing the "auto" state in the shadow to YES/NO.


江ノ島沿線2