[python] azure-iothub-device-client から azure-iot-device への移行について

前提

Azure IOT Edgeのデモを動作させようとしています。

docker image を作成する際に読み込むライブラリが古く、存在しないためイメージを作成できませんでした。
いろいろ調べたのですが、ライブラリが azure-iot-device へと変わっているようです。
そこで、ライブラリを変更しimageを作成し実行したところエラーが発生しました。

古いライブラリ:azure-iothub-device-client
新しいライブラリ:azure-iot-device

実現したいこと

  • azure-iot-device を用いて、index.pyを動かしたい。
    • 正しいパッケージやモジュール名を確認したい

発生している問題・エラーメッセージ

Docker Logs

2023-01-30 15:42:49 Traceback (most recent call last): 2023-01-30 15:42:49 File "./index.py", line 12, in <module> 2023-01-30 15:42:49 from azure.iot.device import IoTHubDeviceClient, IoTHubModuleClient, IoTHubTransportProvider 2023-01-30 15:42:49 ImportError: cannot import name 'IoTHubTransportProvider'

該当のソースコード

python(index.py)

1# Copyright (c) Microsoft. All rights reserved.2# Licensed under the MIT license. See LICENSE file in the project root for3# full license information.4import json 5import random 6import time 7import sys 8#import iothub_client9import azure.iot.device 10 11# pylint: disable=E061112from azure.iot.device import IoTHubDeviceClient, IoTHubModuleClient, IoTHubTransportProvider 13from azure.iot.device import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError 14#from iothub_client import IoTHubClient, IoTHubModuleClient, IoTHubClientError, IoTHubTransportProvider15#from iothub_client import IoTHubMessage, IoTHubMessageDispositionResult, IoTHubError16 17# messageTimeout - the maximum time in milliseconds until a message times out.18# The timeout period starts at IoTHubModuleClient.send_event_async.19# By default, messages do not expire.20MESSAGE_TIMEOUT = 1000021 22# global counters23# Define the JSON message to send to IoT Hub.24TEMPERATURE = 20.025HUMIDITY = 6026MSG_TXT = "{\"temperature\": %.2f,\"humidity\": %.2f}"27# Choose HTTP, AMQP or MQTT as transport protocol. Currently only MQTT is supported.28PROTOCOL = IoTHubTransportProvider.MQTT 29CONNECTION_STRING = "****"30 31# Callback received when the message that we're forwarding is processed.32def send_confirmation_callback(message, result, user_context):33 print ( "IoT Hub responded to message with status: %s" % (result) )34# receive_message_callback is invoked when an incoming message arrives on the specified35# input queue (in the case of this sample, "input1"). Because this is a filter module,36# we forward this message to the "output1" queue.37def receive_message_callback(message, hubManager):38 global RECEIVE_CALLBACKS 39 global TEMPERATURE_THRESHOLD 40 message_buffer = message.get_bytearray()41 size = len(message_buffer)42 message_text = message_buffer[:size].decode('utf-8')43 print ( " Data: <<<%s>>> & Size=%d" % (message_text, size) )44 map_properties = message.properties()45 key_value_pair = map_properties.get_internals()46 print ( " Properties: %s" % key_value_pair )47 RECEIVE_CALLBACKS += 148 print ( " Total calls received: %d" % RECEIVE_CALLBACKS )49 data = json.loads(message_text)50 if "machine" in data and "temperature" in data["machine"] and data["machine"]["temperature"] > TEMPERATURE_THRESHOLD:51 map_properties.add("MessageType", "Alert")52 print("Machine temperature %s exceeds threshold %s" % (data["machine"]["temperature"], TEMPERATURE_THRESHOLD))53 hubManager.forward_event_to_output("output1", message, 0)54 return IoTHubMessageDispositionResult.ACCEPTED 55 56def iothub_client_init():57 # Create an IoT Hub client58 client = IoTHubDeviceClient(CONNECTION_STRING, PROTOCOL)59 return client 60 61# module_twin_callback is invoked when the module twin's desired properties are updated.62def module_twin_callback(update_state, payload, user_context):63 global TWIN_CALLBACKS 64 global TEMPERATURE_THRESHOLD 65 print ( "\nTwin callback called with:\nupdateStatus = %s\npayload = %s\ncontext = %s" % (update_state, payload, user_context) )66 data = json.loads(payload)67 if "desired" in data and "TemperatureThreshold" in data["desired"]:68 TEMPERATURE_THRESHOLD = data["desired"]["TemperatureThreshold"]69 if "TemperatureThreshold" in data:70 TEMPERATURE_THRESHOLD = data["TemperatureThreshold"]71 TWIN_CALLBACKS += 172 print ( "Total calls confirmed: %d\n" % TWIN_CALLBACKS )73 74class HubManager(object):75 76 def __init__(77 self,78 protocol=IoTHubTransportProvider.MQTT):79 self.client_protocol = protocol 80 self.client = IoTHubModuleClient()81 self.client.create_from_environment(protocol)82 83 # set the time until a message times out84 self.client.set_option("messageTimeout", MESSAGE_TIMEOUT)85 # Sets the callback when a module twin's desired properties are updated.86 self.client.set_module_twin_callback(module_twin_callback, self)87 # sets the callback when a message arrives on "input1" queue. Messages sent to88 # other inputs or to the default will be silently discarded.89 self.client.set_message_callback("input1", receive_message_callback, self)90 91 # Forwards the message received onto the next stage in the process.92 def forward_event_to_output(self, outputQueueName, event, send_context):93 self.client.send_event_async(94 outputQueueName, event, send_confirmation_callback, send_context)95 96def main(protocol):97 try:98 print ( "\nPython %s\n" % sys.version )99 print ( "IoT Hub Client for Python" )100 101 hub_manager = HubManager(protocol)102 103 print ( "Starting the IoT Hub Python sample using protocol %s..." % hub_manager.client_protocol )104 print ( "The sample is now waiting for messages and will indefinitely. Press Ctrl-C to exit. ")105 106 client = iothub_client_init()107 while True:108 # Build the message with simulated telemetry values.109 temperature = TEMPERATURE + (random.random() * 15)110 humidity = HUMIDITY + (random.random() * 20)111 msg_txt_formatted = MSG_TXT % (temperature, humidity)112 message = IoTHubMessage(msg_txt_formatted)113 client.send_event_async(message, send_confirmation_callback, None)114 time.sleep(1)115 116 except IoTHubError as iothub_error:117 print ( "Unexpected error %s from IoTHub" % iothub_error )118 return119 except KeyboardInterrupt:120 print ( "IoTHubModuleClient sample stopped" )121 122if __name__ == '__main__':123 main(PROTOCOL)

試したこと

1.ライブラリ変更:

  • azure-iothub-device-client -> azure-iot-device

2.呼び出しライブラリ名の変更:

  • iothub_client -> azure.iot.device

補足情報(FW/ツールのバージョンなど)

デモは IoT Edge 1.1 の環境で作成されています。

IoT Edge 1.1のサポートが終了しているため、IoT Edge 1.4 で動かせるように修正したいと考えています。
IoT Edge 1.4 で、ラズパイをAzure Iot edgeに登録し、SimulatedTemperatureSensorを動かすことはできました。

ライブラリの部分で詰まってしまいました。

コメントを投稿

0 コメント