Search code examples
azure-iot-hubazure-iot-sdkazure-iot-centralazure-iot-hub-device-management

How come a call to Twin.DeviceId is null after provisioning is successful in IoT Hub using DPS?


I have the following code:

           DeviceRegistrationResult dpsRegistrationWithEnrollmentGroupResult = await ProvisionDeviceViaEnrollmentGroupAsync(parameters, devicePrimaryKey, deviceSecondaryKey, cancellationToken);

            // Create Device Client
            var authMethodWithEnrollmentGroup = new DeviceAuthenticationWithRegistrySymmetricKey(dpsRegistrationWithEnrollmentGroupResult.DeviceId, devicePrimaryKey);

            var options = new ClientOptions
            {
                    ModelId = modelId,
            };

            DeviceClient deviceClient = DeviceClient.Create(hostname, authenticationMethod, TransportType.Mqtt, options);

            var twin = await deviceClient .GetTwinAsync();
            DeviceId = twin.DeviceId;

The device is provisioned but the DeviceId is null.

enter image description here

What do I need to do to get the actual DeviceId?


Solution

  • Twin.DeviceId is null on the device IoT hub SDK because it is a shared type (lives in Microsoft.Azure.Devices.Shared.dll) that is used by the IoT hub service SDK and the provisioning service SDK as well. The Twin class has a superset of all the available properties in all 3 scenarios.

    The device IoT hub API only has access to the desired and reported properties of a twin.

    If you want to know the device Id, it should have been provided in the DPS registration call in DeviceRegistrationResult.DeviceId.

    In the v2 preview, the shared assembly is removed because this is a bad experience. Each SDK package has its own types that only contain the properties and functionality relevant to that package.

    The client method has changed from GetTwinAsync(...) to GetTwinPropertiesAsync(...) and the return type is now called TwinProperties with only two child properties: Desired and Reported.

    If you are up for it, please give the preview a try and let us know how it goes for you. The migration guide can help you with breaking changes.