はじめに
デバイスから IoT ハブに利用統計情報を送信してバックエンド アプリケーションで読み取るを参考にサンプルコードを動かしてみます。
接続文字列はAzure CLIを使わずに、コンソールから取得します。
Azure IoTについてはこちらを参照。
準備
IoTデバイスを登録する
Azure IoT Hubコンソール > サイドバー > IoTデバイス > 新規
からデバイスを追加する。
追加できたら、追加したデバイスを選択してプライマリ接続文字列
をコピーしておく。
データを送信する
ダウンロードしたサンプルコードから、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
データが送信されている。
送信したデータを受信する
ダウンロードしたサンプルコードから、ReadDeviceToCloudMessages.js
を開き、38行目あたりのconnectionString
にAzure IoT Hubコンソール > サイドバー > 組み込みのエンドポイント > イベントハブ五感エンドポイント
の値を貼り付ける。
(26行目あたりにeventHubsCompatibleEndpoint
などの変数が用意されていますが、無視します。)
コードはこんな感じになる。
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
受信できた。
まとめ
公式のデバイスから IoT ハブに利用統計情報を送信してバックエンド アプリケーションで読み取るを動かしました。
また、Azure CLIを使わずにコンソールから接続文字列を取得しました。
Azure IoT HubのS1
スケールは月に2~3000円ほどかかるので、試し終わったら忘れずに止めておきましょう。
次回は、M5系のデバイスからデータを送信してみます。