问题描述
我创建了一个非常小的边缘模块,它将遥测数据发送到 IoT 中心并接收直接消息。当我使用
启动我的 IoT Edge 脚本时IoTHubModuleClient.create_from_connection_string(connection_string)
本地一切都很好。它可以发送遥测和接收直接方法请求。
当我将脚本部署为容器中的边缘模块时,它也会发送遥测数据,但无法接收任何直接方法请求:
IoTHubModuleClient.create_from_edge_environment()
我的剥离代码如下所示:
import time
import os
import sys
import asyncio
import threading
from azure.iot.device.aio import IoTHubModuleClient
from azure.iot.device import MethodResponse
async def main():
try:
if not sys.version >= "3.5.3":
raise Exception( "The sample requires python 3.5.3+. Current version of Python: %s" % sys.version )
print ( "IoT Hub Client for Python" )
# For production
module_client = IoTHubModuleClient.create_from_edge_environment()
# For tests
#connection_string = "Here was my connection string :)"
#module_client = IoTHubModuleClient.create_from_connection_string(connection_string)
async def direct_method_received(method_request):
try:
await module_client.send_message("Received Method Request: " + str(method_request.name))
print("Received direct message: {} {}\n".format(str(method_request.name),str(method_request.payload)))
method_response = MethodResponse.create_from_method_request(method_request,200,None)
await module_client.send_method_response(method_response)
except Exception as e:
method_response = MethodResponse.create_from_method_request(method_request,400,payload=logging)
await module_client.send_method_response(method_response)
module_client.on_method_request_received = direct_method_received
await module_client.connect()
await module_client.send_message("Receive Module is running.")
while True:
try:
await asyncio.sleep(10)
except Exception as e:
print("Error: {}".format(str(e)))
except Exception as e:
print("Unexpected error %s \n" % e)
raise
finally:
await module_client.shutdown()
if __name__ == "__main__":
asyncio.run(main())
iotedge 服务说我的模块工作正常。同样正如我所说,它发送遥测数据,我可以在 IoT 中心接收。 直接方法请求与门户一起发送,直接在边缘模块控件中:
错误是
这让我很困惑,因为当我在没有边缘运行时直接连接到我的设备时它正在工作。
这里说你需要一些特定的网络配置,但我不知道怎么做,也不知道这是否是我的问题。
iot edge direct method handler in python
解决方法
我终于可以运行示例了:-)
你能检查一下你是否在requirements.txt中引用了azure-iot-device~=2.5.1
吗?
从 https://github.com/Azure/azure-iot-sdk-python/releases 我看到 v2.3.0 解决了这个问题:
- 为接收方法请求添加了处理程序
- 已弃用的接收方法请求 API
雷内