Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8920

Node.jsでAzure IoT Hubにテレメトリを送信するサンプルコードを動かすメモ

$
0
0

はじめに

デバイスから IoT ハブに利用統計情報を送信してバックエンド アプリケーションで読み取るを参考にサンプルコードを動かしてみます。
Image from Gyazo
接続文字列はAzure CLIを使わずに、コンソールから取得します。

Azure IoTについてはこちらを参照。

準備

  • Node.jsをインストールする(今回はv14.1.0を使用)
  • サンプルコードをダウンロードする
  • 手順を参考に、Iot Hubをデプロイする。(スケールはS1を選択。)

IoTデバイスを登録する

Azure IoT Hubコンソール > サイドバー > IoTデバイス > 新規からデバイスを追加する。

Image from Gyazo

追加できたら、追加したデバイスを選択してプライマリ接続文字列をコピーしておく。

Image from Gyazo

データを送信する

ダウンロードしたサンプルコードから、SimulatedDevice.jsを開き、17行目あたりのconnectionStringに先程コピーしたプライマリ接続文字列を貼り付ける。

コードはこんな感じになる。

varconnectionString='{Your device connection string here}';// ←ここに`プライマリ接続文字列`を貼り付ける。varMqtt=require('azure-iot-device-mqtt').Mqtt;varDeviceClient=require('azure-iot-device').ClientvarMessage=require('azure-iot-device').Message;varclient=DeviceClient.fromConnectionString(connectionString,Mqtt);setInterval(function(){// 送信するデータを生成する。(本当はセンサーで測定した値を入れるがシミュレーションのため乱数を使用)vartemperature=20+(Math.random()*15);varmessage=newMessage(JSON.stringify({temperature:temperature,humidity:60+(Math.random()*20)}));message.properties.add('temperatureAlert',(temperature>30)?'true':'false');console.log('Sending message: '+message.getData());// イベントを送信するclient.sendEvent(message,function(err){if(err){console.error('send error: '+err.toString());}else{console.log('message sent');}});},1000);

以下のコマンドをターミナルで実行する。

$ node SimulatedDevice.js

データが送信されている。

Image from Gyazo

送信したデータを受信する

ダウンロードしたサンプルコードから、ReadDeviceToCloudMessages.jsを開き、38行目あたりのconnectionStringAzure IoT Hubコンソール > サイドバー > 組み込みのエンドポイント > イベントハブ五感エンドポイントの値を貼り付ける。
(26行目あたりにeventHubsCompatibleEndpointなどの変数が用意されていますが、無視します。)

Image from Gyazo

コードはこんな感じになる。

constconnectionString=`Endpoint=**********************;SharedAccessKeyName=*****************;EntityPath=********************`;varprintError=function(err){console.log(err.message);};varprintMessages=function(messages){for(constmessageofmessages){console.log("Telemetry received: ");console.log(JSON.stringify(message.body));console.log("Properties (set by device): ");console.log(JSON.stringify(message.properties));console.log("System properties (set by IoT Hub): ");console.log(JSON.stringify(message.systemProperties));console.log("");}};asyncfunctionmain(){console.log("IoT Hub Quickstarts - Read device to cloud messages.");constclientOptions={// webSocketOptions: {//   webSocket: WebSocket,//   webSocketConstructorOptions: {}// }};constconsumerClient=newEventHubConsumerClient("$Default",connectionString,clientOptions);// イベントハブのストリームからデータを取得するconsumerClient.subscribe({processEvents:printMessages,processError:printError,});}main().catch((error)=>{console.error("Error running sample:",error);});

実行する。

$ node ReadDeviceToCloudMessages.js

受信できた。

Image from Gyazo

まとめ

公式のデバイスから IoT ハブに利用統計情報を送信してバックエンド アプリケーションで読み取るを動かしました。
また、Azure CLIを使わずにコンソールから接続文字列を取得しました。

Azure IoT HubのS1スケールは月に2~3000円ほどかかるので、試し終わったら忘れずに止めておきましょう。

次回は、M5系のデバイスからデータを送信してみます。


Viewing all articles
Browse latest Browse all 8920

Trending Articles