Come funziona

Introduzione

L'API per la registrazione zero-touch consente ai rivenditori di dispositivi di automatizzare la loro integrazione. Gli strumenti di vendita della tua organizzazione possono integrare la registrazione zero-touch, rendendo il tuo gli utenti e i clienti in modo più produttivo. Utilizza l'API per aiutare i tuoi utenti a:

  • Assegnare i dispositivi acquistati all'account di registrazione zero-touch di un cliente.
  • Creazione dell'account di registrazione zero-touch dei clienti.
  • Allegare ai dispositivi lo smartphone e i metadati dell'ordine.
  • Creazione di report sui dispositivi assegnati ai clienti.

Questo documento presenta l'API e spiega i pattern. Se vuoi esplorare l'API autonomamente, prova una guida rapida per Java, .NET o Python.

Concetti delle API

I clienti e i dispositivi sono le risorse principali che utilizzi nell'API. Per creare clienti, chiama il numero create. Puoi creare dispositivi utilizzando i metodi dell'API delle attestazioni (vedi sotto). La tua organizzazione può anche creare clienti e dispositivi utilizzando il portale della registrazione zero-touch.

Relazione tra dispositivo e risorsa cliente

Cliente
Aziende a cui la tua organizzazione vende dispositivi. I clienti hanno un name e ID. Utilizza un cliente quando vuoi rivendicare o trovare i suoi dispositivi. A per saperne di più, consulta Customer.
Dispositivo
Un dispositivo Android o ChromeOS con funzionalità di registrazione zero-touch della tua organizzazione viene venduto a un cliente. I dispositivi hanno ID hardware, metadati e richieste dei clienti. I dispositivi sono fondamentali per l'API, quindi li utilizzi in quasi tutti i metodi. Per scoprire di più, visita la pagina Device.
DeviceIdentifier
Incapsulano gli ID hardware, come IMEI o MEID, per identificare un prodotto dispositivo. Utilizza un DeviceIdentifier per scegliere come target il dispositivo che vuoi trovare, aggiornare o rivendicare. Per saperne di più, leggi Identificatori.
DeviceMetadata
Memorizza coppie chiave-valore di metadati per il dispositivo. Utilizza DeviceMetadata per archiviare i metadati della tua organizzazione. Per approfondire, consulta Metadati del dispositivo.

Per elencare tutti i metodi e le risorse dell'API che la tua app può utilizzare, consulta il riferimento API.

Creare clienti

Per i dispositivi Android, il rivenditore è responsabile della creazione del cliente per conto del cliente. Il cliente utilizzerà questo account per accedere al portale della registrazione zero-touch per configurare le impostazioni di provisioning dispositivi mobili. Questa operazione non è necessaria per i dispositivi ChromeOS, che dispongono già di un Workspace che utilizzerà per configurare le impostazioni di provisioning.

Puoi chiamare il metodo API create per creare account cliente per la registrazione zero-touch. Poiché i clienti vedono il nome dell'azienda nel portale di registrazione zero-touch, l'utente della tua app deve confermare che sia corretto. Non puoi modificare il nome di un cliente dopo averlo creato.

Devi includere almeno un indirizzo email aziendale, associato a un un Account Google, per esserne il proprietario. Non puoi utilizzare account Gmail personali con l'API. Se il cliente ha bisogno di aiuto per associare l'account, inviagli le istruzioni riportate nella pagina Associare un Account Google.

Dopo che avrai creato un cliente chiamando l'API, quest'ultimo gestirà la gestione dei accesso al portale, non puoi modificare che utilizzano l'API. Lo snippet di seguito mostra come creare un cliente:

Java

// Provide the customer data as a Company type.
// The API requires a name and owners.
Company customer = new Company();
customer.setCompanyName("XYZ Corp");
customer.setOwnerEmails(Arrays.asList("liz@example.com", "darcy@example.com"));
customer.setAdminEmails(Collections.singletonList("jane@example.com"));

// Use our reseller ID for the parent resource name.
String parentResource = String.format("partners/%d", PARTNER_ID);

// Call the API to create the customer using the values in the company object.
CreateCustomerRequest body = new CreateCustomerRequest();
body.setCustomer(customer);
Company response = service.partners().customers().create(parentResource, body).execute();

.NET

// Provide the customer data as a Company type.
// The API requires a name and owners.
var customer = new Company
{
    CompanyName = "XYZ Corp",
    OwnerEmails = new String[] { "liz@example.com", "darcy@example.com" },
    AdminEmails = new String[] { "jane@example.com" }
};

// Use our reseller ID for the parent resource name.
var parentResource = String.Format("partners/{0}", PartnerId);

// Call the API to create the customer using the values in the company object.
var body = new CreateCustomerRequest
{
    Customer = customer
};
var request = service.Partners.Customers.Create(body, parentResource);
var response = request.Execute();

Python

# Provide the customer data as a Company type. The API requires
# a name and at least one owner.
company = {'companyName':'XYZ Corp', \
  'ownerEmails':['liz@example.com', 'darcy@example.com'], \
  'adminEmails':['jane@example.com']}

# Use our reseller ID for the parent resource name.
parent_resource = 'partners/{0}'.format(PARTNER_ID)

# Call the API to create the customer using the values in the company object.
response = service.partners().customers().create(parent=parent_resource,
    body={'customer':company}).execute()

Per scoprire di più sui ruoli di proprietario e amministratore per i dipendenti del tuo cliente, consulta Utenti del portale.

Richiedi i dispositivi per i clienti

Dopo aver acquistato i dispositivi, i clienti dovranno configurare le impostazioni di provisioning per questi dispositivi nel loro account. La rivendicazione di un dispositivo lo aggiunge alla registrazione zero-touch e consente al cliente di configurare le impostazioni di provisioning.

Il record di provisioning di un dispositivo ha una sezione per la registrazione zero-touch. Puoi assegnare il dispositivo rivendicando la sezione di registrazione zero-touch del record per un cliente. Chiama il partners.devices.claim oppure partners.devices.claimAsync con come argomento. Fornisci sempre SECTION_TYPE_ZERO_TOUCH come valore per sectionType.

Prima di poter annullare la rivendicazione del dispositivo di un cliente, dovrai annullare la rivendicazione (vedi sotto) richiedere lo stesso dispositivo per un altro cliente. I metodi di rivendicazione convalidare i campi DeviceIdentifier, incluso il codice IMEI, MEID o il numero di serie, il nome del produttore e il modello. ID dispositivo attestato per i dispositivi ChromeOS, durante la creazione di un nuovo dispositivo.

Lo snippet seguente mostra come rivendicare un dispositivo:

Java

// Identify the device to claim.
DeviceIdentifier identifier = new DeviceIdentifier();
// The manufacturer value is optional but recommended for cellular devices
identifier.setManufacturer("Google");
identifier.setImei("098765432109875");

// Create the body to connect the customer with the device.
ClaimDeviceRequest body = new ClaimDeviceRequest();
body.setDeviceIdentifier(identifier);
body.setCustomerId(customerId);
body.setSectionType("SECTION_TYPE_ZERO_TOUCH");

// Claim the device.
ClaimDeviceResponse response = service.partners().devices().claim(PARTNER_ID, body).execute();

.NET

// Identify the device to claim.
var deviceIdentifier = new DeviceIdentifier
{
    // The manufacturer value is optional but recommended for cellular devices
    Manufacturer = "Google",
    Imei = "098765432109875"
};

// Create the body to connect the customer with the device.
ClaimDeviceRequest body = new ClaimDeviceRequest
{
    DeviceIdentifier = deviceIdentifier,
    CustomerId = CustomerId,
    SectionType = "SECTION_TYPE_ZERO_TOUCH"
};

// Claim the device.
var response = service.Partners.Devices.Claim(body, PartnerId).Execute();

Python

# Identify the device to claim.
# The manufacturer value is optional but recommended for cellular devices
device_identifier = {'manufacturer':'Google', 'imei':'098765432109875'}

# Create the body to connect the customer with the device.
request_body = {'deviceIdentifier':device_identifier, \
    'customerId':customer_id, \
    'sectionType':'SECTION_TYPE_ZERO_TOUCH'}

# Claim the device.
response = service.partners().devices().claim(partnerId=PARTNER_ID,
    body=request_body).execute()

Annullamento della rivendicazione dei dispositivi in corso...

La tua organizzazione può annullare la rivendicazione di un dispositivo da parte di un cliente. Se annulli la rivendicazione di un dispositivo, questo viene rimosso dalla registrazione zero-touch. Un rivenditore potrebbe annullare la rivendicazione di un dispositivo vuole eseguire la migrazione a un altro account, restituirlo o che è stato rivendicato per errore. Chiama il metodo partners.devices.unclaim o partners.devices.unclaimAsync per annullare la rivendicazione di un dispositivo da parte di un cliente.

Fornitori

Puoi utilizzare i fornitori per rappresentare i partner rivenditori nella tua rete di concessionari, a livello locale operatori all'interno di una rete di rivenditori globale o qualsiasi organizzazione che vende i dispositivi per tuo conto. I fornitori ti aiutano a separare utenti, clienti e dispositivi:

  • I fornitori che crei non possono vedere il tuo account di registrazione zero-touch né ciascuno account di altre persone.
  • Puoi visualizzare i clienti e i dispositivi dei tuoi fornitori e puoi annullare la registrazione degli stessi. Tuttavia, non puoi assegnare i dispositivi ai clienti dei tuoi fornitori.

Utilizza il portale per creare fornitori per il tuo dell'organizzazione, non puoi utilizzare l'API. Il ruolo del tuo account deve essere Proprietario per creare un nuovo fornitore. Se nella tua organizzazione ci sono fornitori, puoi chiamare partners.vendors.list per elencare le fornitori e partners.vendors.customers.list per attirare i clienti del tuo fornitore. L'esempio seguente utilizza entrambi questi metodi per stampare un report che mostra lo stato dei Termini di servizio per il fornitore clienti:

Java

// First, get the organization's vendors.
String parentResource = String.format("partners/%d", PARTNER_ID);
ListVendorsResponse results = service.partners().vendors().list(parentResource).execute();
if (results.getVendors() == null) {
  return;
}

// For each vendor, report the company name and a maximum 5 customers.
for (Company vendor: results.getVendors()) {
  System.out.format("\n%s customers\n", vendor.getCompanyName());
  System.out.println("---");
  // Use the vendor's API resource name as the parent resource.
  AndroidProvisioningPartner.Partners.Vendors.Customers.List customerRequest =
      service.partners().vendors().customers().list(vendor.getName());
  customerRequest.setPageSize(5);
  ListVendorCustomersResponse customerResponse = customerRequest.execute();

  List<Company> customers = customerResponse.getCustomers();
  if (customers == null) {
    System.out.println("No customers");
    break;
  } else {
    for (Company customer: customers) {
      System.out.format("%s: %s\n",
          customer.getCompanyName(),
          customer.getTermsStatus());
    }
  }
}

.NET

// First, get the organization's vendors.
var parentResource = String.Format("partners/{0}", PartnerId);
var results = service.Partners.Vendors.List(parentResource).Execute();
if (results.Vendors == null)
{
    return;
}

// For each vendor, report the company name and a maximum 5 customers.
foreach (Company vendor in results.Vendors)
{
    Console.WriteLine("\n{0} customers", vendor);
    Console.WriteLine("---");
    // Use the vendor's API resource name as the parent resource.
    PartnersResource.VendorsResource.CustomersResource.ListRequest customerRequest =
        service.Partners.Vendors.Customers.List(vendor.Name);
    customerRequest.PageSize = 5;
    var customerResponse = customerRequest.Execute();

    IList<Company> customers = customerResponse.Customers;
    if (customers == null)
    {
        Console.WriteLine("No customers");
        break;
    }
    else
    {
        foreach (Company customer in customers)
        {
            Console.WriteLine("{0}: {1}", customer.Name, customer.TermsStatus);
        }
    }
}

Python

# First, get the organization's vendors.
parent_resource = 'partners/{0}'.format(PARTNER_ID)
vendor_response = service.partners().vendors().list(
    parent=parent_resource).execute()
if 'vendors' not in vendor_response:
  return

# For each vendor, report the company name and a maximum 5 customers.
for vendor in vendor_response['vendors']:
  print '\n{0} customers'.format(vendor['companyName'])
  print '---'
  # Use the vendor's API resource name as the parent resource.
  customer_response = service.partners().vendors().customers().list(
      parent=vendor['name'], pageSize=5).execute()
  if 'customers' not in customer_response:
    print 'No customers'
    break
  for customer in customer_response['customers']:
    print '  {0}: {1}'.format(customer['name'], customer['termsStatus'])

Se hai un gruppo di dispositivi, potrebbe essere necessario sapere quale rivenditore che il fornitore ha rivendicato il dispositivo. Per ottenere l'ID numerico rivenditore, controlla il valore Il campo resellerId nel record delle rivendicazioni di un dispositivo.

La tua organizzazione può annullare la rivendicazione di un dispositivo rivendicato dal fornitore. Per altre chiamate API modificare i dispositivi, devi verificare che la tua organizzazione abbia rivendicato il dispositivo prima di chiamare il metodo API. L'esempio seguente mostra come eseguire questa operazione:

Java

// Get the devices claimed for two customers: one of our organization's
// customers and one of our vendor's customers.
FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest();
body.setSectionType("SECTION_TYPE_ZERO_TOUCH");
body.setCustomerId(Arrays.asList(resellerCustomerId, vendorCustomerId));
body.setLimit(MAX_PAGE_SIZE);
FindDevicesByOwnerResponse response =
    service.partners().devices().findByOwner(PARTNER_ID, body).execute();
if (response.getDevices() == null) {
  return;
}

for (Device device: response.getDevices()) {
  // Confirm the device was claimed by our reseller and not a vendor before
  // updating metadata in another method.
  for (DeviceClaim claim: device.getClaims()) {
    if (claim.getResellerId() == PARTNER_ID) {
      updateDeviceMetadata(device.getDeviceId());
      break;
    }
  }
}

.NET

// Get the devices claimed for two customers: one of our organization's
// customers and one of our vendor's customers.
FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest
{
    Limit = MaxPageSize,
    SectionType = "SECTION_TYPE_ZERO_TOUCH",
    CustomerId = new List<long?>
    {
        resellerCustomerId,
        vendorCustomerId
    }
};
var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute();
if (response.Devices == null)
{
    return;
}

foreach (Device device in response.Devices)
{
    // Confirm the device was claimed by our reseller and not a vendor before
    // updating metadata in another method.
    foreach (DeviceClaim claim in device.Claims)
    {
        if (claim.ResellerId == PartnerId)
        {
            UpdateDeviceMetadata(device.DeviceId);
            break;
        }
    }
}

Python

# Get the devices claimed for two customers: one of our organization's
# customers and one of our vendor's customers.
request_body = {'limit':MAX_PAGE_SIZE, \
  'pageToken':None, \
  'customerId':[reseller_customer_id, vendor_customer_id], \
  'sectionType':'SECTION_TYPE_ZERO_TOUCH'}
response = service.partners().devices().findByOwner(partnerId=PARTNER_ID,
    body=request_body).execute()

for device in response['devices']:
  # Confirm the device was claimed by our reseller and not a vendor before
  # updating metadata in another method.
  for claim in device['claims']:
    if claim['resellerId'] == PARTNER_ID:
      update_device_metadata(device['deviceId'])
      break

Operazioni batch a lunga esecuzione

L'API include versioni asincrone dei metodi dei dispositivi. Questi metodi consentono l'elaborazione batch di molti dispositivi, mentre elaborano un dispositivo per ogni richiesta API. Nomi dei metodi asincroni Hanno un suffisso Async, ad esempio claimAsync.

I metodi API asincroni restituiscono un risultato prima del completamento dell'elaborazione. I metodi asincroni aiutano anche la tua app (o il tuo strumento) a rimanere reattiva per gli utenti mentre aspettano il completamento di un'operazione di lunga durata. L'app deve controllare periodicamente lo stato dell'operazione.

Operazioni

Puoi utilizzare una Operation per monitorare un'operazione batch a lunga esecuzione. Una chiamata riuscita a un metodo asincrono restituisce un riferimento all'operazione nella risposta. Lo snippet JSON di seguito mostra una risposta tipica dopo la chiamata updateMetadataAsync:

{
  "name": "operations/apibatchoperation/1234567890123476789"
}

Ogni operazione contiene un elenco di singole attività. Chiama operations.get per scoprire le informazioni sullo stato e i risultati delle attività incluse nell'operazione. Lo snippet riportato di seguito mostra come eseguire questa operazione. Nella tua app dovrai gestire eventuali errori.

Java

// Build out the request body to apply the same order number to a customer's
// purchase of 2 devices.
UpdateMetadataArguments firstUpdate = new UpdateMetadataArguments();
firstUpdate.setDeviceMetadata(metadata);
firstUpdate.setDeviceId(firstTargetDeviceId);

UpdateMetadataArguments secondUpdate = new UpdateMetadataArguments();
secondUpdate.setDeviceMetadata(metadata);
secondUpdate.setDeviceId(firstTargetDeviceId);

// Start the device metadata update.
UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest();
body.setUpdates(Arrays.asList(firstUpdate, secondUpdate));
Operation response = service
    .partners()
    .devices()
    .updateMetadataAsync(PARTNER_ID, body)
    .execute();

// Assume the metadata update started, so get the Operation for the update.
Operation operation = service.operations().get(response.getName()).execute();

.NET

// Build out the request body to apply the same order number to a customer's
// purchase of 2 devices.
var updates = new List<UpdateMetadataArguments>
{
    new UpdateMetadataArguments
    {
        DeviceMetadata = metadata,
        DeviceId = firstTargetDeviceId
    },
    new UpdateMetadataArguments
    {
        DeviceMetadata = metadata,
        DeviceId = secondTargetDeviceId
    }
};

// Start the device metadata update.
UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest
{
    Updates = updates
};
var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute();

// Assume the metadata update started, so get the Operation for the update.
Operation operation = service.Operations.Get(response.Name).Execute();

Python

# Build out the request body to apply the same order number to a customer's
# purchase of 2 devices.
updates = [{'deviceMetadata':metadata,'deviceId':first_target_device_id},
    {'deviceMetadata':metadata,'deviceId':second_target_device_id}]

# Start the device metadata update.
response = service.partners().devices().updateMetadataAsync(
    partnerId=PARTNER_ID, body={'updates':updates}).execute()

# Assume the metadata update started, so get the Operation for the update.
operation = service.operations().get(name=response['name']).execute()

Per sapere se un'operazione è stata completata, controlla se è presente un campo done con un valore true. Se manca done o false, l'operazione è ancora in esecuzione.

Risposte

Al termine di un'operazione, l'API aggiorna l'operazione con il risultato, anche se tutte o nessuna delle singole attività sono andate a buon fine. Il campo response è un DevicesLongRunningOperationResponse oggetto che descrive l'elaborazione di ciascun dispositivo nell'operazione.

Controlla il campo successCount per capire in modo efficiente se qualche attività non è riuscita evitare di ripetere l'iterazione tramite lunghi elenchi di risultati. Il campo perDeviceStatus di DevicesLongRunningOperationResponse è un elenco di Istanze di OperationPerDevice con i dettagli di ogni dispositivo l'operazione. L'ordine dell'elenco corrisponde alle attività nella richiesta originale.

Ogni attività di OperationPerDevice contiene un campo result e un riepilogo del promemoria delle richieste ricevute dal server. Controlla se l'attività è riuscita o meno utilizzando il campo result.

Lo snippet JSON di seguito mostra parte di una risposta tipica di un'operazione dopo una chiamata a updateMetadataAsync:

"response": {
  "perDeviceStatus": [
    {
      "result": {
        "deviceId": "12345678901234567",
        "status": "SINGLE_DEVICE_STATUS_SUCCESS"
      },
      "updateMetadata": {
        "deviceId": "12345678901234567",
        "deviceMetadata": {
          "entries": {
            "phonenumber": "+1 (800) 555-0100"
          }
        }
      }
    }
  ],
  "successCount": 1
}

Monitora i progressi

Se la tua app deve monitorare i progressi, devi recuperare periodicamente il operativa. Il campo metadata contiene un'istanza DevicesLongRunningOperationMetadata per aiutare la tua app a controllare gli ultimi progressi di un'operazione in esecuzione. Utilizza i campi di DevicesLongRunningOperationMetadata elencati nella tabella di seguito per monitorare l'avanzamento dell'operazione:

Campo Utilizzo tipico
processingStatus Passa da BATCH_PROCESS_PENDING a BATCH_PROCESS_IN_PROGRESS e poi a BATCH_PROCESS_PROCESSED man mano che l'operazione procede.
progress La percentuale di aggiornamenti elaborati. La tua app può usare questo per stimare l'ora di fine. Poiché progress può essere 100 al termine dell'operazione, controlla il campo done di un'operazione per sapere se completato e ha un risultato.
devicesCount Mostra il numero di aggiornamenti nell'operazione. Questo potrebbe essere diverso dal numero di aggiornamenti se l'API non è in grado di analizzare alcuni aggiornamenti.

L'esempio semplificato riportato di seguito mostra come un'app potrebbe utilizzare i metadati relativi all'avanzamento per impostare gli intervalli di polling. Nella tua app, potresti aver bisogno di un task runner più sofisticato per l'esecuzione di polling. Dovrai anche aggiungere la gestione degli errori.

Java

// Milliseconds between polling the API.
private static long MIN_INTERVAL = 2000;
private static long MAX_INTERVAL = 10000;

// ...
// Start the device metadata update.
Operation response = service
    .partners()
    .devices()
    .updateMetadataAsync(PARTNER_ID, body)
    .execute();
String operationName = response.getName();

// Start polling for completion.
long startTime = new Date().getTime();
while (true) {

  // Get the latest update on the operation's progress using the API.
  Operation operation = service.operations().get(operationName).execute();

  if (operation.get("done") != null && operation.getDone()) {
    // The operation is finished. Print the status.
    System.out.format("Operation complete: %s of %s successful device updates\n",
        operation.getResponse().get("successCount"),
        operation.getMetadata().get("devicesCount"));
    break;

  } else {
    // Estimate how long the operation *should* take - within min and max value.
    BigDecimal opProgress = (BigDecimal) operation.getMetadata().get("progress");
    double progress = opProgress.longValue();
    long interval = MAX_INTERVAL;
    if (progress > 0) {
      interval = (long) ((new Date().getTime() - startTime) *
          ((100.0 - progress) / progress));
    }
    interval = Math.max(MIN_INTERVAL, Math.min(interval, MAX_INTERVAL));

    // Sleep until the operation should be complete.
    Thread.sleep(interval);
  }
}

.NET

// Milliseconds between polling the API.
private static double MinInterval = 2000;
private static double MaxInterval = 10000;

// ...
// Start the device metadata update.
var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute();
var operationName = response.Name;

// Start polling for completion.
var startTime = DateTime.Now;
while (true)
{

    // Get the latest update on the operation's progress using the API.
    Operation operation = service.Operations.Get(operationName).Execute();

    if (operation.Done == true)
    {
        // The operation is finished. Print the status.
        Console.WriteLine("Operation complete: {0} of {1} successful device updates",
                          operation.Response["successCount"],
                          operation.Metadata["devicesCount"]);
        break;
    }
    else
    {
        // Estimate how long the operation *should* take - within min and max value.
        double progress = (double)(long)operation.Metadata["progress"];
        double interval = MaxInterval;
        if (progress > 0)
        {
            interval = DateTime.Now.Subtract(startTime).TotalMilliseconds *
                                     ((100.0 - progress) / progress);
        }
        interval = Math.Max(MinInterval, Math.Min(interval, MaxInterval));

        // Sleep until the operation should be complete.
        System.Threading.Thread.Sleep((int)interval);
    }
}

Python

# Seconds between polling the API.
MIN_INTERVAL = 2;
MAX_INTERVAL = 10;

# ...
# Start the device metadata update
response = service.partners().devices().updateMetadataAsync(
  partnerId=PARTNER_ID, body={'updates':updates}).execute()

op_name = response['name']
start_time = time.time()

# Start polling for completion
while True:
  # Get the latest update on the operation's progress using the API
  op = service.operations().get(name=op_name).execute()

  if 'done' in op and op['done']:
    # The operation is finished. Print the status.
    print('Operation complete: {0} of {1} successful device updates'.format(
      op['response']['successCount'], op['metadata']['devicesCount']
    ))
    break
  else:
    # Estimate how long the operation *should* take - within min and max.
    progress = op['metadata']['progress']
    interval = MIN_INTERVAL
    if progress > 0:
      interval = (time.time() - start_time) * ((100.0 - progress) / progress)
    interval = max(MIN_INTERVAL, min(interval, MAX_INTERVAL))

    # Sleep until the operation should be complete.
    time.sleep(interval)

Scegli un approccio ai sondaggi che sia pertinente per gli utenti della tua app. Alcuni utenti di app potrebbero trarre vantaggio da aggiornamenti regolari sullo stato se si attendono completato.

Risultati paginati

Il metodo API partners.devices.findByOwner potrebbe restituire elenchi di dispositivi molto lunghi. Per ridurre le dimensioni della risposta, questo e altri metodi API (ad esempio partners.devices.findByIdentifier) supportano i risultati paginati. Con i risultati paginati, l'applicazione può richiedere ed elaborare in modo iterativo elenchi di grandi dimensioni una pagina alla volta.

Dopo aver chiamato il metodo API, controlla se la risposta include un valore per nextPageToken Se nextPageToken non è null, la tua app può utilizzarlo per recuperare un'altra pagina di dispositivi chiamando nuovamente il metodo. Devi impostare un limite superiore per il numero di dispositivi nel parametro limit. Se nextPageToken è null, la tua app ha richiesto il l'ultima pagina.

Il metodo di esempio riportato di seguito mostra in che modo la tua app potrebbe stampare un elenco di dispositivi, uno: pagina alla volta:

Java

private static long MAX_PAGE_SIZE = 10;

// ...
/**
 * Demonstrates how to loop through paginated lists of devices.
 * @param pageToken       The token specifying which result page to return.
 * @throws IOException    If the zero-touch API call fails.
 */
private void printDevices(String pageToken) throws IOException {

  // Create the request body to find the customer's devices.
  FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest();
  body.setLimit(MAX_PAGE_SIZE);
  body.setSectionType("SECTION_TYPE_ZERO_TOUCH");
  body.setCustomerId(Collections.singletonList(targetCustomerId));

  // Call the API to get a page of Devices. Send a page token from the method
  // argument (might be None). If the page token is None, the API returns the first page.
  FindDevicesByOwnerResponse response =
      service.partners().devices().findByOwner(PARTNER_ID, body).execute();
  if (response.getDevices() == null) {
    return;
  }

  // Print the devices included in this page of results.
  for (Device device: response.getDevices()) {
    System.out.format("Device %s\n", device.getName());
  }
  System.out.println("---");

  // Check to see if another page of devices is available. If yes,
  // fetch and print the devices.
  if (response.getNextPageToken() != null) {
    this.printDevices(response.getNextPageToken());
  }
}

// ...
// Pass null to start printing the first page of devices.
printDevices(null);

.NET

private static int MaxPageSize = 10;

// ...
/// <summary>Demonstrates how to loop through paginated lists of devices.</summary>
/// <param name="pageToken">The token specifying which result page to return.</param>
private void PrintDevices(string pageToken)
{
    // Create the request body to find the customer's devices.
    FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest
    {
        PageToken = pageToken,
        Limit = MaxPageSize,
        SectionType = "SECTION_TYPE_ZERO_TOUCH",
        CustomerId = new List<long?>
        {
            targetCustomerId
        }
    };

    // Call the API to get a page of Devices. Send a page token from the method
    // argument (might be None). If the page token is None, the API returns the first page.
    var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute();
    if (response.Devices == null)
    {
        return;
    }

    // Print the devices included in this page of results.
    foreach (Device device in response.Devices)
    {
        Console.WriteLine("Device: {0}", device.Name);
    }
    Console.WriteLine("---");

    // Check to see if another page of devices is available. If yes,
    // fetch and print the devices.
    if (response.NextPageToken != null)
    {
        this.PrintDevices(response.NextPageToken);
    }
}

// ...
// Pass null to start printing the first page of devices.
PrintDevices(null);

Python

MAX_PAGE_SIZE = 10;

# ...
def print_devices(page_token):
  """Demonstrates how to loop through paginated lists of devices.

  Args:
    page_token: The token specifying which result page to return.
  """

   # Create the body to find the customer's devices.
  request_body = {'limit':MAX_PAGE_SIZE, \
    'pageToken':page_token, \
    'customerId':[target_customer_id], \
    'sectionType':'SECTION_TYPE_ZERO_TOUCH'}

  # Call the API to get a page of Devices. Send a page token from the method
  # argument (might be None). If the page token is None,
  # the API returns the first page.
  response = service.partners().devices().findByOwner(partnerId=PARTNER_ID,
    body=request_body).execute()

  # Print the devices included in this page of results.
  for device in response['devices']:
    print 'Device: {0}'.format(device['name'])
  print '---'

  # Check to see if another page of devices is available. If yes,
  # fetch and print the devices.
  if 'nextPageToken' in response:
    print_devices(response['nextPageToken'])

# ...
# Pass None to start printing the first page of devices.
print_devices(None);

Passaggi successivi

Ora che sai come funziona l'API, prova gli esempi con una guida rapida per Java, .NET o Python. Puoi utilizzare un colab per visualizzare esempi di chiamate API e sperimentare la chiamata dell'API.