Search code examples
azure-iot-hubazure-iot-sdk

Create device with extra fields tags of device twin in Azure IoT Hub


Is it possible to define a property in tags of deviceTwin while creating a device in Azure IoT Hub? or it is needed to create device first, then get and update the deviceTwin. It seems 'Registry.create' (from node sdk) does not accept such an option. What is I want to achieve is following

`...
const device ={
    deviceId: '1',
    tags: {
        location: 'London'
    }
}
registry.create(device, callback)
...`

Solution

  • It is impossible to define a property in the tags of Device Twin while creating a device by using Registry in node. In fact, the create method in Registry class is calling the PUT REST API to create or update device. The device information should be referred to the Request Body, it does not accept properties items in request body.

    However, there is a way to work around. You can use Bulk Create Or Update Devices to create a new device with tags and properties.

    For example, post the request body as following:

    [
        {"Id":"7ADF1F8E-0208-49B7-B62A-021323EF1B55","tags":{"location": "London"},"properties":{"desired":{"Temperature":30}},"Status":"enable","importMode":"create"},
        {"Id":"F2805601-1F4D-459F-9D8F-E2F7D3638EF5","tags":{"location": "New York"},"properties":{"desired":{"Temperature":31}},"Status":"enable","importMode":"create"},
        {"Id":"D0447599-5B2D-4EDB-A809-29643CC7E30E","tags":{"location": "Paris"},"properties":{"desired":{"Temperature":32}},"Status":"enable","importMode":"create"}
    ]
    

    After that, you will find the tags and desired property in device twin.

    enter image description here