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");
}
Aggregations