无法从 python 向 Azure IoTHub 发送 E2C 消息

Unable to send E2C Message to Azure IoTHub from python

我在模拟器上创建,该模拟器将模拟边缘到云消息从模拟设备发送到 IoT 中心。我在遵循官方文档和 SDK 的 GitHub 页面中的代码时 运行 遇到了一些问题。

这是我的代码:

async def send_e2c_message(self):
   # ConnectionString get from IoT Hub
   conn_str = "HostName={IoTHubName};SharedAccessKeyName=service;SharedAccessKey={SomeAccessKey}"

   # The client object is used to interact with the Azure IoT hub.
   device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

   # Connect the client.
   await device_client.connect()

   # Send message
   print("Sending message...")
   await device_client.send_message('Hello World')
   print("Message successfully sent!")

   # Disconnect client
   await device_client.disconnect()


if __name__ == "__main__":
    asyncio.run(IoTHubAccessor.send_e2c_message(self))

报错如下:

Unexpected error in <azure.iot.device.iothub.pipeline.pipeline_stages_iothub.UseAuthProviderStage object at 0x03E31CF0>._execute_op() call
Traceback (most recent call last):
  File 
  ...
in _execute_op
    sas_token=self.auth_provider.get_current_sas_token(),
  File 
  ...
in get_current_sas_token
    self.generate_new_sas_token()
  File 
resource_uri = self.hostname + "/devices/" + self.device_id
TypeError: can only concatenate str (not "NoneType") to str
UseAuthProviderStage(SetAuthProviderOperation): completing with error can only concatenate str (not "NoneType") to str
Exception caught in background thread.  Unable to handle.

File 
"...\pipeline_stages_mqtt.py", line 37, in _cancel_pending_connection_op
    op = self._pending_connection_op
AttributeError: 'MQTTTransportStage' object has no attribute '_pending_connection_op'
MQTTTransportStage(ConnectOperation): completing with error 'MQTTTransportStage' object has no attribute '_pending_connection_op'
SerializeConnectOpsStage(ConnectOperation): completing with error 'MQTTTransportStage' object has no attribute '_pending_connection_op'
Unhandled exception in background thread
This may cause the background thread to abort and may result in system instability.

我得到的图片是我必须提供一些 DeviceId,但是,连接字符串中的 DeviceId 不起作用。我不知道放在哪里。

我只是按照官方文档给出的样例,不知道是什么问题。如果有人能提供帮助,我将不胜感激。

谢谢。

您使用了错误的连接字符串。由于您要从 device-side 发送消息,您需要使用设备连接字符串: