首页 > 解决方案 > Unable to send E2C Message to Azure IoTHub from python

问题描述

I was creating on a simulator which sends simulate edge-to-cloud message from the simulated device to IoT Hub. I ran into some issues while I following the code in official documentation and GitHub pages of the SDK.

Here's my code:

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))

The error shows are as below:

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.

I get the picture that I have to provide somewhat the DeviceId, however, the DeviceId in the connection string won't work. I have no idea where to put it.

I merely just follow the sample given by official documentation so I do not know what is the problem. If anyone could help I really appreciates it.

Thank you.

标签: pythonazureazure-iot-hub

解决方案


You are using the wrong connection string. Since you want to send messages from the device-side, you need to use a device connection string:

enter image description here

enter image description here


推荐阅读