Create a gateway

Create a new gateway with a given ID, public key, and authentication method.

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 CreateGateway(string projectId, string cloudRegion,
    string registryName, string gatewayId, string publicKeyFilePath,
    string algorithm)
{
    var cloudIot = CreateAuthorizedClient();
    var registryPath = $"projects/{projectId}/locations/{cloudRegion}"
        + $"/registries/{registryName}";
    Console.WriteLine("Creating gateway with id: {0}", gatewayId);

    Device body = new Device()
    {
        Id = gatewayId,
        GatewayConfig = new GatewayConfig()
        {
            GatewayType = "GATEWAY",
            GatewayAuthMethod = "ASSOCIATION_ONLY"
        },
        Credentials =
        new List<DeviceCredential>()
        {
            new DeviceCredential()
            {
                PublicKey = new PublicKeyCredential()
                {
                    Key = File.ReadAllText(publicKeyFilePath),
                    Format = (algorithm == "ES256" ?
                        "ES256_PEM" : "RSA_X509_PEM")
                },
            }
        }
    };

    Device createdDevice = cloudIot.Projects.Locations.Registries
        .Devices.Create(body, registryPath).Execute();
    Console.WriteLine("Created gateway: {0}", createdDevice.ToString());
    return 0;
}

Go


// createGateway creates a new IoT Core gateway with a given id, public key, and auth method.
// gatewayAuthMethod can be one of: ASSOCIATION_ONLY, DEVICE_AUTH_TOKEN_ONLY, ASSOCIATION_AND_DEVICE_AUTH_TOKEN.
// https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices#gatewayauthmethod
func createGateway(w io.Writer, projectID string, region string, registryID string, gatewayID string, gatewayAuthMethod string, publicKeyPath string) (*cloudiot.Device, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

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

	gateway := &cloudiot.Device{
		Id: gatewayID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "RSA_X509_PEM",
					Key:    string(keyBytes),
				},
			},
		},
		GatewayConfig: &cloudiot.GatewayConfig{
			GatewayType:       "GATEWAY",
			GatewayAuthMethod: gatewayAuthMethod,
		},
	}

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

	fmt.Fprintln(w, "Successfully created gateway:", gatewayID)

	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);

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

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

String keyFormat = "RSA_X509_PEM";
if ("ES256".equals(algorithm)) {
  keyFormat = "ES256_PEM";
}

PublicKeyCredential publicKeyCredential = new PublicKeyCredential();

byte[] keyBytes = java.nio.file.Files.readAllBytes(Paths.get(certificateFilePath));
publicKeyCredential.setKey(new String(keyBytes, StandardCharsets.US_ASCII));
publicKeyCredential.setFormat(keyFormat);
DeviceCredential deviceCredential = new DeviceCredential();
deviceCredential.setPublicKey(publicKeyCredential);

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

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

Node.js

// const cloudRegion = 'us-central1';
// const deviceId = 'my-unauth-device';
// const gatewayId = 'my-gateway';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
// const gatewayAuthMethod = 'ASSOCIATION_ONLY';
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);

  console.log('Creating gateway:', gatewayId);

  let credentials = [];

  // if public key format and path are specified, use those
  if (publicKeyFormat && publicKeyFile) {
    credentials = [
      {
        publicKey: {
          format: publicKeyFormat,
          key: readFileSync(publicKeyFile).toString(),
        },
      },
    ];
  }

  const device = {
    id: gatewayId,
    credentials: credentials,
    gatewayConfig: {
      gatewayType: 'GATEWAY',
      gatewayAuthMethod: gatewayAuthMethod,
    },
  };

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

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

createDevice();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\Device;
use Google\Cloud\Iot\V1\DeviceCredential;
use Google\Cloud\Iot\V1\GatewayAuthMethod;
use Google\Cloud\Iot\V1\GatewayConfig;
use Google\Cloud\Iot\V1\GatewayType;
use Google\Cloud\Iot\V1\PublicKeyCredential;
use Google\Cloud\Iot\V1\PublicKeyFormat;

/**
 * Create a new gateway with the given id and certificate file.
 *
 * @param string $registryId IOT Gateway Registry ID
 * @param string $gatewayId IOT Gateway ID
 * @param string $certificateFile Path to certificate file.
 * @param string $algorithm the algorithm used for JWT (ES256 or RS256).
 * @param string $projectId Google Cloud project ID
 * @param string $location (optional) Google Cloud region
 */
function create_gateway(
    $registryId,
    $gatewayId,
    $certificateFile,
    $algorithm,
    $projectId,
    $location = 'us-central1'
) {
    print('Creating new Gateway' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    $publicKeyFormat = PublicKeyFormat::ES256_PEM;
    if ($algorithm == 'RS256') {
        $publicKeyFormat = PublicKeyFormat::RSA_X509_PEM;
    }

    $gatewayConfig = (new GatewayConfig())
        ->setGatewayType(GatewayType::GATEWAY)
        ->setGatewayAuthMethod(GatewayAuthMethod::ASSOCIATION_ONLY);

    $publicKey = (new PublicKeyCredential())
        ->setFormat($publicKeyFormat)
        ->setKey(file_get_contents($certificateFile));

    $credential = (new DeviceCredential())
        ->setPublicKey($publicKey);

    $device = (new Device())
        ->setId($gatewayId)
        ->setGatewayConfig($gatewayConfig)
        ->setCredentials([$credential]);

    $gateway = $deviceManager->createDevice($registryName, $device);

    printf('Gateway: %s : %s' . PHP_EOL,
        $gateway->getNumId(),
        $gateway->getId());
}

Python

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# gateway_id = 'your-gateway-id'
# certificate_file = 'path/to/certificate.pem'
# algorithm = 'ES256'
# Check that the gateway doesn't already exist
exists = False
client = iot_v1.DeviceManagerClient()

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 == gateway_id:
        exists = True
    print(
        "Device: {} : {} : {} : {}".format(
            device.id, device.num_id, device.config, device.gateway_config
        )
    )

with io.open(certificate_file) as f:
    certificate = f.read()

if algorithm == "ES256":
    certificate_format = iot_v1.PublicKeyFormat.ES256_PEM
else:
    certificate_format = iot_v1.PublicKeyFormat.RSA_X509_PEM

# TODO: Auth type
device_template = {
    "id": gateway_id,
    "credentials": [
        {"public_key": {"format": certificate_format, "key": certificate}}
    ],
    "gateway_config": {
        "gateway_type": iot_v1.GatewayType.GATEWAY,
        "gateway_auth_method": iot_v1.GatewayAuthMethod.ASSOCIATION_ONLY,
    },
}

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

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to create a gateway in"
# gateway_id  = "The identifier of the gateway to create"
# cert_path   = "The path to the certificate"
# alg         = "ES256 || RS256"

require "google/apis/cloudiot_v1"

# Initialize the client and authenticate with the specified scope
Cloudiot   = Google::Apis::CloudiotV1
iot_client = Cloudiot::CloudIotService.new
iot_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the project
parent = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

device = Cloudiot::Device.new
device.id = gateway_id

certificate_format = if alg == "ES256"
                       "ES256_PEM"
                     else
                       "RSA_X509_PEM"
                     end

pubkey = Google::Apis::CloudiotV1::PublicKeyCredential.new
pubkey.key = File.read cert_path
pubkey.format = certificate_format

cred = Google::Apis::CloudiotV1::DeviceCredential.new
cred.public_key = pubkey

device.credentials = [cred]

gateway_config = Google::Apis::CloudiotV1::GatewayConfig.new
gateway_config.gateway_type = "GATEWAY"
gateway_config.gateway_auth_method = "ASSOCIATION_ONLY"

device.gateway_config = gateway_config

# Create the Gateway
device = iot_client.create_project_location_registry_device parent, device

puts "Gateway: #{device.id}"
puts "\tBlocked: #{device.blocked}"
puts "\tLast Event Time: #{device.last_event_time}"
puts "\tLast State Time: #{device.last_state_time}"
puts "\tName: #{device.name}"

What's next

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