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?

Databricks にて Azure IoT Hub に対してファイルをアップロードする方法

Posted at

概要

Databricks にて Azure IoT Hub に対してファイルをアップロードする方法を共有します。

事前準備

環境構築

  • Azure IoT Hub の構築 (本手順は Free tier で実施)
  • Databricks (本手順は Serveless ではなく汎用コンピュートで実行)
  • Azure Storage

デバイスの作成と接続文字列の取得

Azure IoT Hub のリソース画面にて、デバイスタブを選択後、+ デバイスの追加を選択します。

image.png

デバイス IDに任意の値を入力し、保存を選択してデバイスを作成します。

image.png

作成したデバイスを表示して、プライマリ接続文字列コピー済みを選択して値をコピーします。

image.png

Azure Storage に対する Azure IoT Hub への権限付与を実施

IoT hub の画面にて、 ID -> システム割り当てを選択し、状態オンに設定します。

image.png

Azure Storage の画面にて、IoT Hub のマネージド ID に対してストレージ BLOB データ共同作成者権限を付与します。

image.png

IoT Hub の画面にて、ファイルのアップロード -> Azure Storage コンテナーの選択を選択します。

image.png

ファイルアップロード先のストレージアカウントとコンテナーを選択して、選択を選択します。

image.png

保存を選択します。

image.png

アップロードする方法

アップロードするファイルを確認します。

from PIL import Image
import matplotlib.pyplot as plt

img = Image.open('/dbfs/databricks-datasets/flower_photos/daisy/100080576_f52e8ee070_n.jpg')
plt.imshow(img)
plt.axis('off')

image.png

必要なライブラリをインストールします。

%pip install azure-iot-device -q
%pip install azure.storage.blob -q
dbutils.library.restartPython()

image.png

下記のコードを実行して、ファイルのアップロードを実施します。

device_conn_str = "HostName=iot-hub-test-001.azure-devices.net;DeviceId=qiita_test_01;SharedAccessKey=r2fxXUdn/4w9iNJdhqnIJZ+h0qxxxxx="

image.png

source_dir = "/dbfs/databricks-datasets/flower_photos/daisy/100080576_f52e8ee070_n.jpg"
target_dir  = f"databricks/test.jpg"
from azure.iot.device import IoTHubDeviceClient
from azure.storage.blob import BlobClient

device = IoTHubDeviceClient.create_from_connection_string(device_conn_str)
device.connect()

info = device.get_storage_info_for_blob(target_dir)
sas  = f"https://{info['hostName']}/{info['containerName']}/{info['blobName']}{info['sasToken']}"
blob = BlobClient.from_blob_url(sas)
with open(source_dir, "rb") as fh:
    blob.upload_blob(fh, overwrite=True)

device.notify_blob_upload_status(
    correlation_id=info["correlationId"],
    is_success=True,
    status_code=200,
    status_description="OK"
)
device.disconnect()

image.png

Azure Storge 上にファイルが保存されていることを確認します。

image.png

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?