Google Cloud IoT Core verrà ritirato il 16 agosto 2023. Per saperne di più, contatta il team dedicato al tuo account Google Cloud.

Elenco di gateway

Elenca tutti i gateway in un registro specifico.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, consulta quanto segue:

Esempio di codice

Go

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Go.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


// listGateways lists all the gateways in a specific registry.
func listGateways(w io.Writer, projectID string, region string, registryID 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
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.Devices.List(parent).GatewayListOptionsGatewayType("GATEWAY").Do()

	if err != nil {
		return nil, fmt.Errorf("ListGateways: %w", err)
	}

	if len(response.Devices) == 0 {
		fmt.Fprintln(w, "No gateways found")
		return response.Devices, nil
	}

	fmt.Fprintln(w, len(response.Devices), "devices:")
	for _, gateway := range response.Devices {
		fmt.Fprintf(w, "\t%s\n", gateway.Id)
	}

	return response.Devices, nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Java.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

GoogleCredentials credential =
    GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = GsonFactory.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> gateways =
    service
        .projects()
        .locations()
        .registries()
        .devices()
        .list(registryPath)
        .setGatewayListOptionsGatewayType("GATEWAY")
        .execute()
        .getDevices();

if (gateways != null) {
  System.out.println("Found " + gateways.size() + " devices");
  for (Device d : gateways) {
    System.out.println("Id: " + d.getId());
    if (d.getConfig() != null) {
      // Note that this will show the device config in Base64 encoded format.
      System.out.println("Config: " + d.getGatewayConfig().toPrettyString());
    }
    System.out.println();
  }
} else {
  System.out.println("Registry has no devices.");
}

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Node.js.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// const cloudRegion = 'us-central1';
// 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 listDevices() {
  // Construct request
  const registryPath = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );

  console.log('Current gateways in registry:');
  const [response] = await iotClient.listDevices({
    parent: registryPath,
    fieldMask: {paths: ['config', 'gateway_config']},
  });
  const devices = response;

  devices.forEach(device => {
    if (
      device.gatewayConfig !== undefined &&
      device.gatewayConfig.gatewayType === 'GATEWAY'
    ) {
      console.log('----\n', device);
    }
  });
}

listDevices();

PHP

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core PHP.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\GatewayType;
use Google\Protobuf\FieldMask;

/**
 * List gateways in the registry.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function list_gateways(
    $registryId,
    $projectId,
    $location = 'us-central1'
) {
    print('Listing gateways' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();

    // Format the full registry path
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    // Pass field mask to retrieve the gateway configuration fields
    $fieldMask = (new FieldMask())->setPaths(['config', 'gateway_config']);

    // Call the API
    $devices = $deviceManager->listDevices($registryName, [
        'fieldMask' => $fieldMask
    ]);

    // Print the result
    $foundGateway = false;
    foreach ($devices->iterateAllElements() as $device) {
        $gatewayConfig = $device->getGatewayConfig();
        $gatewayType = null;
        if ($gatewayConfig != null) {
            $gatewayType = $gatewayConfig->getGatewayType();
        }

        if ($gatewayType == GatewayType::GATEWAY) {
            $foundGateway = true;
            printf('Device: %s : %s' . PHP_EOL,
                $device->getNumId(),
                $device->getId());
        }
    }
    if (!$foundGateway) {
        printf('Registry %s has no gateways' . PHP_EOL, $registryId);
    }
}

Python

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Python.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
client = iot_v1.DeviceManagerClient()

path = client.registry_path(project_id, cloud_region, registry_id)
mask = gp_field_mask.FieldMask()
mask.paths.append("config")
mask.paths.append("gateway_config")
devices = list(client.list_devices(request={"parent": path, "field_mask": mask}))

for device in devices:
    if device.gateway_config is not None:
        if device.gateway_config.gateway_type == 1:
            print("Gateway ID: {}\n\t{}".format(device.id, device))

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Ruby.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region for the registry"
# registry_id = "The registry to list gateways in"

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
resource = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

# List the devices in the provided region
gateways = iot_client.list_project_location_registry_devices(
  resource, field_mask: "config,gatewayConfig"
)

puts "Gateways:"
if gateways.devices && gateways.devices.any?
  gateways.devices.each do |gateway|
    if gateway.gateway_config && gateway.gateway_config.gateway_type == "GATEWAY"
      puts "\t#{gateway.id}"
    end
  end
else
  puts "\tNo gateways found in this registry."
end

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.