azure: connection dropped error when trying to get twin properties

Hamza Outa 61 Reputation points
2023-06-21T11:30:46.31+00:00

I use the device provisioning service to provision a "fake" iot device (using example code). I can then use the python SDK to send messages. But every time I run the line:

twin = await device_client.get_twin()

I immediately get this exception:

Exception caught in background thread.  Unable to handle.
['azure.iot.device.common.transport_exceptions.ConnectionDroppedError: Unexpected disconnection\n']

I tried something where I had one script constantly sending messages to the hub, and a second script where I try to get the twin properties. The moment the second scripts reaches the get_twin function both scripts crash with that exception.

How can I retrieve the twin properties without getting that exception

my code for getting twin properties:

from azure.iot.device.aio import IoTHubDeviceClient
import asyncio

# Configuration
device_connection_string = ""

async def get_desired_properties():
    device_client = IoTHubDeviceClient.create_from_connection_string(device_connection_string)

    # Connect to the device
    await device_client.connect()

    # Get the twin
    twin = await device_client.get_twin()
    desired_properties = twin["desired"]

    # Process desired properties
    if desired_properties:
        print("Desired properties:")
        print(desired_properties)
    else:
        print("No desired properties found.")

    # Disconnect from the device
    await device_client.disconnect()

if __name__ == "__main__":
    asyncio.run(get_desired_properties())

script I use the send messages:

while True:
    # Send telemetry message
    telemetry_data = "Sample telemetry message"
    await device_client.send_message(telemetry_data)
    print(f"Telemetry sent: {telemetry_data}")
    # Wait for a specific time interval
    await asyncio.sleep(30)
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,189 questions
Azure IoT SDK
Azure IoT SDK
An Azure software development kit that facilitates building applications that connect to Azure IoT services.
219 questions
{count} votes

Accepted answer
  1. LeelaRajeshSayana-MSFT 15,241 Reputation points Microsoft Employee
    2023-06-21T14:26:33.7633333+00:00

    Hi @Hamza Outa Greetings! Thank you for posting this question here.

    You are encountering this error because you are trying to use the same device connection string from two different client applications simultaneously. This device connection string is not meant to be used by different clients. It is supposed to be used from a single device.

    To overcome this error and achieve what you are looking for, you can leverage the Service shared access policy of IoT Hub and use the below code to get the device twin properties.

    from azure.iot.hub import IoTHubRegistryManager
    
    # Connection string for the IoT Hub service shared access policy
    CONNECTION_STRING = "<IoTHubServiceConnectionString>"
    DEVICE_ID = "TestDevice1"
    
    
    def get_device_twin():
        # Create an instance of the IoTHubRegistryManager
        registry_manager = IoTHubRegistryManager.from_connection_string(
            CONNECTION_STRING)
    
        try:
            # Get the device twin
            twin = registry_manager.get_twin(DEVICE_ID)
            print("Device Twin:")
            print(twin)
    
            desired_properties = twin.properties.desired
    
        # Process desired properties
            if desired_properties:
                print("Desired properties:")
                print(desired_properties)
            else:
                print("No desired properties found.")
    
        except Exception as e:
            print("Error getting device twin:", str(e))
    
    
    # Call the function to get the device twin
    get_device_twin()
    
    

    You can get the connection string for Service policy by navigating to Security settings on IoT Hub --> Shared Access Policies --> service --> Primary Connection string.

    Hope this helps. Please let us know if you have any additional questions or need further clarifications on this.


    If the response helped, please do click Accept Answer and Yes. Doing so would help other community members with similar issue identify the solution. I highly appreciate your contribution to the community.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.