Search code examples
google-cloud-platformiotgoogle-cloud-iot

Copy device from one registry to another Google IoT Core


I have one device, 'XYZ' in test registry as i have to follow an entire process to check few things. Then after it is successful, i want to register this device to proper registry, say camera registry and following with unregister from test registry. So, is copying a device-object from one registry to another possible? If not, what is the best approach to do this?


Solution

  • The registry of a device cannot be updated, and there's no feature to copy one device from one registry to another. So, the best approach on this depends on your use case.

    I created a small Python script that can migrate the devices, I tested it in some of mine and it seems to work correctly for all their properties.

    from google.cloud import iot_v1
    
    def move_device(project_id, cloud_region, registry_source, registry_target, device_id):
    
        # Instantiate client
        client = iot_v1.DeviceManagerClient()
    
        # Source device path to get its information, and deleting it
        source_device_path = client.device_path(project_id, cloud_region, registry_source, device_id)
    
        # Get device
        device = client.get_device(source_device_path)
    
        # Clean values for new device
        device.name = ''
        device.config.cloud_update_time.seconds= 0
        device.config.cloud_update_time.nanos= 0
        device.config.version = 0 
        device.num_id = 0
    
        # Create the device in the new registry
        client.create_device(client.registry_path(project_id, cloud_region, registry_target), device)
    
        # Uncomment to delete the original device registry
        # client.delete_device(source_device_path)
    
    if __name__ == "__main__":
    
        project_id='my-project'
        cloud_region='my-region'
        registry_source='my-registry-source'
        registry_target='my-registry-target'
        device_id='my-device'
    
        move_device(project_id, cloud_region, registry_source, registry_target, device_id)
    

    This script is using the google-cloud-iot library, which you can install with pip.

    pip install google-cloud-iot
    

    I took the idea from the documentation, I hope it works for you.