清除注册表

从注册表中移除所有设备并删除注册表。

代码示例

Java

如需了解详情,请参阅 Cloud IoT Core Java API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

protected static void clearRegistry(String cloudRegion, String projectId, String registryName)
    throws GeneralSecurityException, IOException {
  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);

  CloudIot.Projects.Locations.Registries regAlias = service.projects().locations().registries();
  CloudIot.Projects.Locations.Registries.Devices devAlias = regAlias.devices();

  ListDevicesResponse listGatewaysRes =
      devAlias.list(registryPath).setGatewayListOptionsGatewayType("GATEWAY").execute();
  List<Device> gateways = listGatewaysRes.getDevices();

  // Unbind all devices from all gateways
  if (gateways != null) {
    System.out.println("Found " + gateways.size() + " devices");
    for (Device g : gateways) {
      String gatewayId = g.getId();
      System.out.println("Id: " + gatewayId);

      ListDevicesResponse res =
          devAlias
              .list(registryPath)
              .setGatewayListOptionsAssociationsGatewayId(gatewayId)
              .execute();
      List<Device> deviceNumIds = res.getDevices();

      if (deviceNumIds != null) {
        System.out.println("Found " + deviceNumIds.size() + " devices");
        for (Device device : deviceNumIds) {
          String deviceId = device.getId();
          System.out.println(String.format("ID: %s", deviceId));

          // Remove any bindings from the device
          UnbindDeviceFromGatewayRequest request = new UnbindDeviceFromGatewayRequest();
          request.setDeviceId(deviceId);
          request.setGatewayId(gatewayId);
          regAlias.unbindDeviceFromGateway(registryPath, request).execute();
        }
      } else {
        System.out.println("Gateway has no bound devices.");
      }
    }
  }

  // Remove all devices from the regsitry
  List<Device> devices = devAlias.list(registryPath).execute().getDevices();

  if (devices != null) {
    System.out.println("Found " + devices.size() + " devices");
    for (Device d : devices) {
      String deviceId = d.getId();
      String devicePath = String.format("%s/devices/%s", registryPath, deviceId);
      service.projects().locations().registries().devices().delete(devicePath).execute();
    }
  }

  // Delete the registry
  service.projects().locations().registries().delete(registryPath).execute();
}

后续步骤

如需搜索并过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器