🕸️
Azure IoT Hubをつかってみる-コードベースでAzure IoT hubにメッセージ送信
はじめに
前回のIoT hubをベースに、コードベースでメッセージの送信を確認します。
本記事の作業範囲
- 前記事の環境(Azure IoT Hub)をベースにする
- .NETでのコードから、デバイスとしてクラウド側にメッセージを送信する
- メッセージがAzure内のストレージに保存されることを確認する
関連記事
- Azure Portalでの環境構築とVSCode IoT拡張機能によるメッセージ送信
- コードベースでAzure IoT hubにメッセージ送信🔴本記事🔴
- ラズパイからAzure IoT hubにメッセージ送信
- クラウド側のメッセージをデバイスで受信
作業手順
vscode拡張機能 - iot hubをコードのひな形を作成する
- デバイスを右クリックし、"Generate Code"を選択する
- "C#"を選択する
- "Send device-to-cloud message"を選択する
- ディレクトリ選択画面に遷移する(任意のディレクトリを選択)
- コードのひな形が作成される
コードを修正する
現時点(2025.3)で、ひな形のコードは動作しません
プロジェクトの設定を見直します
- 今回は、TargetFrameworkをnet8.0に変更しました
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.*" /> </ItemGroup> </Project>
自動生成されたコードは、ダミーの温度・湿度を送信するコードになっています。
温度湿度は不要なため、削除します。
また、前記事のiot hubルーティングにて、メッセージに"status=error"を含める必要があります。
下記が修正したコードとになります。
using System;
using Microsoft.Azure.Devices.Client;
using System.Text;
using System.Threading.Tasks;
namespace SimulatedDevice
{
class SimulatedDevice
{
// DeviceClientはIoT Hubとの通信を管理します
private static DeviceClient s_deviceClient;
// IoT Hubへの接続文字列(認証に使用)
private const string s_connectionString = "HostName=studyiot.azure-devices.net;DeviceId=iotdev1;SharedAccessKeyName=device;SharedAccessKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// IoT Hubにメッセージを送信する非同期メソッド
private static async void SendDeviceToCloudMessagesAsync()
{
while (true)
{
// エラーステータスを示すJSON形式のメッセージを作成
var messageString = "{'status':'error', 'message':'error from code'}";
// メッセージ内容をバイト配列に変換し、Messageオブジェクトを生成
var message = new Message(Encoding.ASCII.GetBytes(messageString))
{
// メッセージのコンテンツタイプとエンコーディングを設定
ContentType = "application/json",
ContentEncoding = "utf-8"
};
// IoT Hubへメッセージを非同期に送信
await s_deviceClient.SendEventAsync(message).ConfigureAwait(false);
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
// 次の送信まで10秒間待機
await Task.Delay(10000).ConfigureAwait(false);
}
}
// アプリケーションのエントリーポイント
private static void Main()
{
Console.WriteLine("IoT Hub Quickstarts - Simulated device. Ctrl-C to exit.\n");
// MQTTプロトコルを使用してIoT Hubに接続
s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt);
// 非同期でメッセージ送信を開始
SendDeviceToCloudMessagesAsync();
// コンソールアプリケーションが終了しないよう、ユーザーの入力待機
Console.ReadLine();
}
}
}
ビルドと実行
ターミナルからビルドし、実行する
d2c> dotnet build simulated-device.csproj
MSBuild のバージョン 17.9.6+a4ecab324 (.NET)
復元対象のプロジェクトを決定しています...
復元対象のすべてのプロジェクトは最新です。
simulated-device -> d2c\bin\Debug\net8.0\simulated-device.dll
ビルドに成功しました。
0 個の警告
0 エラー
経過時間 00:00:03.04
PS d2c> dotnet run --project simulated-device.csproj
IoT Hub Quickstarts - Simulated device. Ctrl-C to exit.
2025/03/29 16:27:04 > Sending message: {'status':'error', 'message':'error from code6a'}
2025/03/29 16:27:15 > Sending message: {'status':'error', 'message':'error from code6a'}
2025/03/29 16:27:25 > Sending message: {'status':'error', 'message':'error from code6a'}
Azure側を確認(ストレージのコンテナを確認)
-
指定したストレージコンテナをみるとjsonファイル(分名)が存在する
-
上記のファイルを開く
{"EnqueuedTimeUtc":"2025-03-29T07:27:13.0360000Z","Properties":{},"SystemProperties":{"connectionDeviceId":"iotdev1","connectionAuthMethod":"{\"scope\":\"hub\",\"type\":\"sas\",\"issuer\":\"iothub\"}","connectionDeviceGenerationId":"638787901862736111","contentType":"application/json","contentEncoding":"utf-8","enqueuedTime":"2025-03-29T07:27:13.0360000Z"},"Body":{'status':'error', 'message':'error from code'}}
{"EnqueuedTimeUtc":"2025-03-29T07:27:14.0510000Z","Properties":{},"SystemProperties":{"connectionDeviceId":"iotdev1","connectionAuthMethod":"{\"scope\":\"hub\",\"type\":\"sas\",\"issuer\":\"iothub\"}","connectionDeviceGenerationId":"638787901862736111","contentType":"application/json","contentEncoding":"utf-8","enqueuedTime":"2025-03-29T07:27:14.0510000Z"},"Body":{'status':'error', 'message':'error from code'}}
{"EnqueuedTimeUtc":"2025-03-29T07:27:24.2230000Z","Properties":{},"SystemProperties":{"connectionDeviceId":"iotdev1","connectionAuthMethod":"{\"scope\":\"hub\",\"type\":\"sas\",\"issuer\":\"iothub\"}","connectionDeviceGenerationId":"638787901862736111","contentType":"application/json","contentEncoding":"utf-8","enqueuedTime":"2025-03-29T07:27:24.2230000Z"},"Body":{'status':'error', 'message':'error from code'}}
送信データを確認できました
まとめ
コードから送信できるようになりました
次は、実際のデバイス(ラズパイ)を使ってメッセージ送信をしたいと思います
GitHubで編集を提案
Discussion