0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

functionsで受信し、他のデバイスに転送する処理

Last updated at Posted at 2025-05-23

デバイスから他のデバイスに転送するメモ

デバイスから Azure IoT Hub に送られたデータを他のデバイスに転送する方法を書いてます。

デバイス送信処理

const { Client, Message } = require('azure-iot-device');
const { Mqtt } = require('azure-iot-device-mqtt');

// 接続文字列(Azure Portalから取得)
const connectionString = '<Your IoT Hub device connection string>';
const client = Client.fromConnectionString(connectionString, Mqtt);

// デバイスから送信するデータ
const temperature = 25.3;
const humidity = 60.1;

const data = JSON.stringify({
  temperature,
  humidity,
  timestamp: new Date().toISOString()
});

const message = new Message(data);
message.contentType = 'application/json';
message.contentEncoding = 'utf-8';

client.open((err) => {
  if (err) {
    console.error('接続失敗: ' + err.message);
  } else {
    console.log('IoT Hub に接続されました。メッセージを送信します...');
    client.sendEvent(message, (err) => {
      if (err) {
        console.error('送信失敗: ' + err.toString());
      } else {
        console.log('メッセージ送信成功:\n' + data);
      }
      client.close(); // 接続終了
    });
  }
});

Functions受信処理

import { app } from '@azure/functions';

app.eventHub('eventHubTrigger', {
  connection: 'IoTHubConnection',
  eventHubName: 'messages/events',
  consumerGroup: '$Default',
  cardinality: 'many',
  handler: async (messages, context) => {
    for (const [i, msg] of messages.entries()) {
      try {
        // EventData.body から payload を取得
        const payload =
          typeof msg.body === 'string'
            ? JSON.parse(msg.body)
            : msg.body; // すでにオブジェクトならそのまま使う

        const deviceId = msg.systemProperties?.['iothub-connection-device-id'];

        context.log(`📦 メッセージ ${i + 1}`);
        context.log(`📟 デバイスID: ${deviceId}`);
        context.log(`🌡️ 温度: ${payload.temperature}`);
        context.log(`💧 湿度: ${payload.humidity}`);
        context.log(`🕒 タイムスタンプ: ${payload.timestamp}`);
      } catch (err) {
        context.log.error(`❌ メッセージ処理エラー:`, err.message);
      }
    }
  }
});
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?