Search in sources :

Example 1 with SendCommandToDeviceRequest

use of com.google.api.services.cloudiot.v1.model.SendCommandToDeviceRequest in project java-docs-samples by GoogleCloudPlatform.

the class DeviceRegistryExample method sendCommand.

// [END iot_set_iam_policy]
/**
 * Send a command to a device. *
 */
// [START iot_send_command]
protected static void sendCommand(String deviceId, String projectId, String cloudRegion, String registryName, String data) throws GeneralSecurityException, IOException {
    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 devicePath = String.format("projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryName, deviceId);
    SendCommandToDeviceRequest req = new SendCommandToDeviceRequest();
    // Data sent through the wire has to be base64 encoded.
    Base64.Encoder encoder = Base64.getEncoder();
    String encPayload = encoder.encodeToString(data.getBytes(StandardCharsets.UTF_8.name()));
    req.setBinaryData(encPayload);
    System.out.printf("Sending command to %s%n", devicePath);
    service.projects().locations().registries().devices().sendCommandToDevice(devicePath, req).execute();
    System.out.println("Command response: sent");
}
Also used : CloudIot(com.google.api.services.cloudiot.v1.CloudIot) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) Base64(java.util.Base64) JsonFactory(com.google.api.client.json.JsonFactory) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) SendCommandToDeviceRequest(com.google.api.services.cloudiot.v1.model.SendCommandToDeviceRequest) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Aggregations

HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)1 JsonFactory (com.google.api.client.json.JsonFactory)1 CloudIot (com.google.api.services.cloudiot.v1.CloudIot)1 SendCommandToDeviceRequest (com.google.api.services.cloudiot.v1.model.SendCommandToDeviceRequest)1 HttpCredentialsAdapter (com.google.auth.http.HttpCredentialsAdapter)1 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)1 Base64 (java.util.Base64)1