Create a device

Create a device in a registry.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

C#

public static object CreateDevice(string projectId, string cloudRegion, string registryName, string deviceId)
{
    var cloudIot = CreateAuthorizedClient();
    var registryPath = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryName}";

    var req = cloudIot
        .Projects
        .Locations
        .Registries
        .Devices
        .List(registryPath);
    req.FieldMask = "config,gatewayConfig";
    var devices = req.Execute().Devices;
    if (devices != null)
    {
        Console.WriteLine("Found {0} devices", devices.Count);
        devices.ToList().ForEach(singleDevice =>
        {
            if ((singleDevice.Id != null && singleDevice.Id.Equals(deviceId))
            || (singleDevice.Name != null && singleDevice.Name.Equals(deviceId)))
            {
                Console.WriteLine("Device exists, skipping. ");
                return;
            }
        }
        );
    }
    Console.WriteLine("Creating device with id: {0}", deviceId);

    GatewayConfig gwConfig = new GatewayConfig()
    {
        GatewayType = "NON_GATEWAY",
        GatewayAuthMethod = "ASSOCIATION_ONLY"
    };

    Device device = new Device()
    {
        Id = deviceId,
        GatewayConfig = gwConfig
    };

    Device createdDevice =
        cloudIot
            .Projects
            .Locations
            .Registries
            .Devices
            .Create(device, registryPath)
            .Execute();

    Console.WriteLine("Created device: {0}", createdDevice.ToString());
    return 0;
}

Go


// createDevice creates a device in a registry with one of the following public key formats:
// RSA_PEM, RSA_X509_PEM, ES256_PEM, ES256_X509_PEM, UNAUTH.
func createDevice(w io.Writer, projectID string, region string, registryID string, deviceID string, publicKeyFormat string, keyPath string) (*cloudiot.Device, error) {
	client, err := getClient()
	if err != nil {
		return nil, err
	}

	keyBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return nil, err
	}

	var device cloudiot.Device

	// If no credentials are passed in, create an unauth device.
	if publicKeyFormat == "UNAUTH" {
		device = cloudiot.Device{
			Id: deviceID,
		}
	} else {
		device = cloudiot.Device{
			Id: deviceID,
			Credentials: []*cloudiot.DeviceCredential{
				{
					PublicKey: &cloudiot.PublicKeyCredential{
						Format: publicKeyFormat,
						Key:    string(keyBytes),
					},
				},
			},
		}
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.Devices.Create(parent, &device).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Successfully created a device with %s public key: %s", publicKeyFormat, deviceID)

	return response, nil
}

Java

GoogleCredentials credential =
    GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
final CloudIot service =
    new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
        .setApplicationName(APP_NAME)
        .build();

final String registryPath =
    String.format(
        "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

List<Device> devices =
    service
        .projects()
        .locations()
        .registries()
        .devices()
        .list(registryPath)
        .setFieldMask("config,gatewayConfig")
        .execute()
        .getDevices();

if (devices != null) {
  System.out.println("Found " + devices.size() + " devices");
  for (Device d : devices) {
    if ((d.getId() != null && d.getId().equals(deviceId))
        || (d.getName() != null && d.getName().equals(deviceId))) {
      System.out.println("Device exists, skipping.");
      return;
    }
  }
}

System.out.println("Creating device with id: " + deviceId);
Device device = new Device();
device.setId(deviceId);

GatewayConfig gwConfig = new GatewayConfig();
gwConfig.setGatewayType("NON_GATEWAY");
gwConfig.setGatewayAuthMethod("ASSOCIATION_ONLY");

device.setGatewayConfig(gwConfig);
Device createdDevice =
    service
        .projects()
        .locations()
        .registries()
        .devices()
        .create(registryPath, device)
        .execute();

System.out.println("Created device: " + createdDevice.toPrettyString());

Node.js

// const cloudRegion = 'us-central1';
// const deviceId = 'my-device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const iot = require('@google-cloud/iot');

const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);
  const device = {
    id: deviceId,
    credentials: [
      {
        publicKey: {
          format: publicKeyFormat,
          key: readFileSync(publicKeyFile).toString(),
        },
      },
    ],
  };

  const request = {
    parent: regPath,
    device,
  };

  const [response] = await iotClient.createDevice(request);
  console.log('Created device', response);
}

createDevice();

Python

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'

# Check that the device doesn't already exist
client = iot_v1.DeviceManagerClient()

exists = False

parent = client.registry_path(project_id, cloud_region, registry_id)

devices = list(client.list_devices(request={"parent": parent}))

for device in devices:
    if device.id == device_id:
        exists = True

# Create the device
device_template = {
    "id": device_id,
    "gateway_config": {
        "gateway_type": iot_v1.GatewayType.NON_GATEWAY,
        "gateway_auth_method": iot_v1.GatewayAuthMethod.ASSOCIATION_ONLY,
    },
}

if not exists:
    res = client.create_device(
        request={"parent": parent, "device": device_template}
    )
    print("Created Device {}".format(res))
else:
    print("Device exists, skipping")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.