LoginSignup
0
0

More than 3 years have passed since last update.

Azure IoT Hub に Node.js で subscribe

Last updated at Posted at 2021-01-19

Ubuntu 20.10 で確認しました。

azure_subscribe.js
#! /usr/bin/node
// ---------------------------------------------------------------
//  azure_subscribe.js
//
//                  Jan/19/2021
//
// ---------------------------------------------------------------
'use strict'

const { EventHubConsumerClient } = require("@azure/event-hubs");

const eventHubsCompatibleEndpoint = "sb://ihsuprodkwres017dednamespace.servicebus.windows.net/"

const eventHubsCompatiblePath = "iothub-ehub-iot-aa-344012-58f0095d47"

const iotHubSasKey = "QThy0z2eiCOzKcv2Ni5DZCnHL8Gtabcdefghd4pj5D4="

const connectionString = `Endpoint=${eventHubsCompatibleEndpoint};EntityPath=${eventHubsCompatiblePath};SharedAccessKeyName=service;SharedAccessKey=${iotHubSasKey}`;

var printError = function (err) {
  console.log(err.message);
};

var printMessages = function (messages) {
  for (const message of messages) {
    console.log("Telemetry received: ");
    console.log(JSON.stringify(message.body));
    console.log("");
/*
    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("");
*/
  }
};

async function main() {
  console.log("IoT Hub Quickstarts - Read device to cloud messages.");

  const clientOptions = {
  };

  const consumerClient = new EventHubConsumerClient("$Default", connectionString, clientOptions);

  consumerClient.subscribe({
    processEvents: printMessages,
    processError: printError,
  });
}

main().catch((error) => {
  console.error("Error running sample:", error);
});

// ---------------------------------------------------------------

必要な値の取得方法

Event Hub-compatible endpoint

az iot hub show --query properties.eventHubEndpoints.events.endpoint --name {
your IoT Hub name}

Event Hub-compatible name

az iot hub show --query properties.eventHubEndpoints.events.path --name {your
 IoT Hub name}

Primary key for the "service" policy to read messages

az iot hub policy show --name service --query primaryKey --hub-name {your IoT
 Hub name}

Portal にアクセスして、connectionString を読み取ることもできます。
「イベントハブ互換エンドポイント」になります。
iothub_endpoint_jan20.png

実行コマンド

export NODE_PATH=/usr/lib/node_modules
./azure_subscribe.js

参考ページ
Hub からテレメトリを読み取る

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0