Search in sources :

Example 1 with GetNamedShadowSubscriptionRequest

use of software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest in project aws-greengrass-nucleus by aws-greengrass.

the class ShadowDeploymentE2ETest method GIVEN_device_deployment_WHEN_shadow_update_messages_gets_delivered_out_of_order_THEN_shadow_updated_with_latest_deployment_status.

@Test
void GIVEN_device_deployment_WHEN_shadow_update_messages_gets_delivered_out_of_order_THEN_shadow_updated_with_latest_deployment_status() throws Exception {
    CreateDeploymentRequest createDeploymentRequest = CreateDeploymentRequest.builder().targetArn(thingInfo.getThingArn()).components(Utils.immutableMap("CustomerApp", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build(), "SomeService", ComponentDeploymentSpecification.builder().componentVersion("1.0.0").build())).build();
    draftAndCreateDeployment(createDeploymentRequest);
    assertThat(kernel.getMain()::getState, eventuallyEval(is(State.FINISHED)));
    IotShadowClient shadowClient = new IotShadowClient(new WrapperMqttClientConnection(kernel.getContext().get(MqttClient.class)));
    UpdateNamedShadowSubscriptionRequest req = new UpdateNamedShadowSubscriptionRequest();
    req.shadowName = DEPLOYMENT_SHADOW_NAME;
    req.thingName = thingInfo.getThingName();
    CountDownLatch reportSucceededCdl = new CountDownLatch(1);
    CountDownLatch deviceSyncedStateToSucceededCdl = new CountDownLatch(1);
    AtomicReference<HashMap<String, Object>> reportedSection = new AtomicReference<>();
    AtomicReference<Integer> shadowVersionWhenDeviceFirstReportedSuccess = new AtomicReference<>();
    AtomicReference<Integer> shadowVersionWhenDeviceReportedInProgress = new AtomicReference<>();
    shadowClient.SubscribeToUpdateNamedShadowAccepted(req, QualityOfService.AT_LEAST_ONCE, (response) -> {
        try {
            logger.info("Got shadow update: {}", new ObjectMapper().writeValueAsString(response));
        } catch (JsonProcessingException e) {
        // ignore
        }
        if (response.state.reported == null) {
            return;
        }
        String reportedStatus = (String) response.state.reported.get(STATUS_KEY);
        if (JobStatus.IN_PROGRESS.toString().equals(reportedStatus)) {
            reportedSection.set(response.state.reported);
            shadowVersionWhenDeviceReportedInProgress.set(response.version);
        } else if (JobStatus.SUCCEEDED.toString().equals(reportedStatus)) {
            // state to SUCCESS second time the shadow version
            if (reportSucceededCdl.getCount() == 0 && response.version > shadowVersionWhenDeviceFirstReportedSuccess.get()) {
                deviceSyncedStateToSucceededCdl.countDown();
            }
            shadowVersionWhenDeviceFirstReportedSuccess.set(response.version);
            reportSucceededCdl.countDown();
        }
    });
    // waiting for the device to report success
    assertTrue(reportSucceededCdl.await(60, TimeUnit.SECONDS));
    // Updating the shadow with deployment status IN_PROGRESS to simulate out-of-order update of shadow
    ShadowState shadowState = new ShadowState();
    shadowState.reported = reportedSection.get();
    UpdateNamedShadowRequest updateNamedShadowRequest = new UpdateNamedShadowRequest();
    updateNamedShadowRequest.shadowName = DEPLOYMENT_SHADOW_NAME;
    updateNamedShadowRequest.thingName = thingInfo.getThingName();
    updateNamedShadowRequest.state = shadowState;
    shadowClient.PublishUpdateNamedShadow(updateNamedShadowRequest, QualityOfService.AT_LEAST_ONCE).get(30, TimeUnit.SECONDS);
    // verify that the device updates shadow state to SUCCEEDED
    assertTrue(deviceSyncedStateToSucceededCdl.await(60, TimeUnit.SECONDS));
    // Updating the shadow with a lower version number to trigger a message to /update/rejected event
    shadowState = new ShadowState();
    shadowState.reported = reportedSection.get();
    updateNamedShadowRequest = new UpdateNamedShadowRequest();
    updateNamedShadowRequest.shadowName = DEPLOYMENT_SHADOW_NAME;
    updateNamedShadowRequest.thingName = thingInfo.getThingName();
    updateNamedShadowRequest.state = shadowState;
    updateNamedShadowRequest.version = shadowVersionWhenDeviceReportedInProgress.get();
    shadowClient.PublishUpdateNamedShadow(updateNamedShadowRequest, QualityOfService.AT_LEAST_ONCE).get(30, TimeUnit.SECONDS);
    CountDownLatch deviceRetrievedShadowCdl = new CountDownLatch(1);
    GetNamedShadowSubscriptionRequest getNamedShadowSubscriptionRequest = new GetNamedShadowSubscriptionRequest();
    getNamedShadowSubscriptionRequest.shadowName = DEPLOYMENT_SHADOW_NAME;
    getNamedShadowSubscriptionRequest.thingName = thingInfo.getThingName();
    shadowClient.SubscribeToGetNamedShadowAccepted(getNamedShadowSubscriptionRequest, QualityOfService.AT_MOST_ONCE, getShadowResponse -> {
        deviceRetrievedShadowCdl.countDown();
    }).get(30, TimeUnit.SECONDS);
    // verify that the device retrieved the shadow when an update operation was rejected.
    assertTrue(deviceRetrievedShadowCdl.await(60, TimeUnit.SECONDS));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) ComponentDeploymentSpecification(software.amazon.awssdk.services.greengrassv2.model.ComponentDeploymentSpecification) HashMap(java.util.HashMap) Coerce(com.aws.greengrass.util.Coerce) StringUtils(org.apache.commons.lang3.StringUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) STATUS_KEY(com.aws.greengrass.status.DeploymentInformation.STATUS_KEY) BaseE2ETestCase(com.aws.greengrass.integrationtests.e2e.BaseE2ETestCase) ShadowState(software.amazon.awssdk.iot.iotshadow.model.ShadowState) UpdateNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) State(com.aws.greengrass.dependency.State) IotShadowClient(software.amazon.awssdk.iot.iotshadow.IotShadowClient) GGExtension(com.aws.greengrass.testcommons.testutilities.GGExtension) Tag(org.junit.jupiter.api.Tag) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) DEPLOYMENT_SHADOW_NAME(com.aws.greengrass.deployment.ShadowDeploymentListener.DEPLOYMENT_SHADOW_NAME) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ComponentConfigurationUpdate(software.amazon.awssdk.services.greengrassv2.model.ComponentConfigurationUpdate) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) TestUtils(com.aws.greengrass.testcommons.testutilities.TestUtils) EventuallyLambdaMatcher.eventuallyEval(com.github.grantwest.eventually.EventuallyLambdaMatcher.eventuallyEval) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Topics(com.aws.greengrass.config.Topics) Slf4jLogAdapter(com.aws.greengrass.logging.impl.Slf4jLogAdapter) WrapperMqttClientConnection(com.aws.greengrass.mqttclient.WrapperMqttClientConnection) CountDownLatch(java.util.concurrent.CountDownLatch) AfterEach(org.junit.jupiter.api.AfterEach) Utils(com.aws.greengrass.util.Utils) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) CreateDeploymentRequest(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentRequest) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) MqttClient(com.aws.greengrass.mqttclient.MqttClient) Matchers.is(org.hamcrest.Matchers.is) GreengrassLogMessage(com.aws.greengrass.logging.impl.GreengrassLogMessage) GetNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest) HashMap(java.util.HashMap) CreateDeploymentRequest(software.amazon.awssdk.services.greengrassv2.model.CreateDeploymentRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) WrapperMqttClientConnection(com.aws.greengrass.mqttclient.WrapperMqttClientConnection) UpdateNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest) CountDownLatch(java.util.concurrent.CountDownLatch) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) IotShadowClient(software.amazon.awssdk.iot.iotshadow.IotShadowClient) GetNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest) ShadowState(software.amazon.awssdk.iot.iotshadow.model.ShadowState) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Example 2 with GetNamedShadowSubscriptionRequest

use of software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest in project aws-iot-device-sdk-java-v2 by aws.

the class IotShadowClient method SubscribeToGetNamedShadowAccepted.

/**
 * Subscribes to the accepted topic for the GetNamedShadow operation.
 *
 * Once subscribed, `handler` is invoked each time a message matching
 * the `topic` is received. It is possible for such messages to arrive before
 * the SUBACK is received.
 *
 * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-mqtt.html#get-accepted-pub-sub-topic
 *
 * @param request Subscription request configuration
 * @param qos Maximum requested QoS that server may use when sending messages to the client.
 *            The server may grant a lower QoS in the SUBACK
 * @param handler callback function to invoke with messages received on the subscription topic
 * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message
 *
 * @return a future containing the MQTT packet id used to perform the subscribe operation
 */
public CompletableFuture<Integer> SubscribeToGetNamedShadowAccepted(GetNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<GetShadowResponse> handler, Consumer<Exception> exceptionHandler) {
    String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/get/accepted";
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null thingName"));
        return result;
    }
    topic = topic.replace("{thingName}", request.thingName);
    if (request.shadowName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null shadowName"));
        return result;
    }
    topic = topic.replace("{shadowName}", request.shadowName);
    Consumer<MqttMessage> messageHandler = (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            GetShadowResponse response = gson.fromJson(payload, GetShadowResponse.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    };
    return connection.subscribe(topic, qos, messageHandler);
}
Also used : UpdateShadowResponse(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowResponse) NamedShadowUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.NamedShadowUpdatedSubscriptionRequest) ShadowUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSubscriptionRequest) DeleteShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteShadowSubscriptionRequest) UpdateShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest) ShadowUpdatedEvent(software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedEvent) GetNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowRequest) HashMap(java.util.HashMap) EnumSerializer(software.amazon.awssdk.iot.EnumSerializer) CompletableFuture(java.util.concurrent.CompletableFuture) DeleteNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowSubscriptionRequest) GsonBuilder(com.google.gson.GsonBuilder) ByteBuffer(java.nio.ByteBuffer) NamedShadowDeltaUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.NamedShadowDeltaUpdatedSubscriptionRequest) ShadowState(software.amazon.awssdk.iot.iotshadow.model.ShadowState) ShadowUpdatedSnapshot(software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSnapshot) UpdateNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) ShadowMetadata(software.amazon.awssdk.iot.iotshadow.model.ShadowMetadata) Gson(com.google.gson.Gson) GetShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest) GetShadowResponse(software.amazon.awssdk.iot.iotshadow.model.GetShadowResponse) DeleteShadowRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteShadowRequest) ShadowStateWithDelta(software.amazon.awssdk.iot.iotshadow.model.ShadowStateWithDelta) DeleteNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowRequest) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ShadowDeltaUpdatedEvent(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedEvent) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ShadowDeltaUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest) StandardCharsets(java.nio.charset.StandardCharsets) GetShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest) Consumer(java.util.function.Consumer) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) Timestamp(software.amazon.awssdk.iot.Timestamp) ErrorResponse(software.amazon.awssdk.iot.iotshadow.model.ErrorResponse) ShadowStateFactory(software.amazon.awssdk.iot.ShadowStateFactory) DeleteShadowResponse(software.amazon.awssdk.iot.iotshadow.model.DeleteShadowResponse) GetNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UpdateShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowRequest) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) GetShadowResponse(software.amazon.awssdk.iot.iotshadow.model.GetShadowResponse) CompletableFuture(java.util.concurrent.CompletableFuture) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with GetNamedShadowSubscriptionRequest

use of software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest in project aws-iot-device-sdk-java-v2 by aws.

the class IotShadowClient method SubscribeToGetNamedShadowRejected.

/**
 * Subscribes to the rejected topic for the GetNamedShadow operation.
 *
 * Once subscribed, `handler` is invoked each time a message matching
 * the `topic` is received. It is possible for such messages to arrive before
 * the SUBACK is received.
 *
 * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-mqtt.html#get-rejected-pub-sub-topic
 *
 * @param request Subscription request configuration
 * @param qos Maximum requested QoS that server may use when sending messages to the client.
 *            The server may grant a lower QoS in the SUBACK
 * @param handler callback function to invoke with messages received on the subscription topic
 * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message
 *
 * @return a future containing the MQTT packet id used to perform the subscribe operation
 */
public CompletableFuture<Integer> SubscribeToGetNamedShadowRejected(GetNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) {
    String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/get/rejected";
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null thingName"));
        return result;
    }
    topic = topic.replace("{thingName}", request.thingName);
    if (request.shadowName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null shadowName"));
        return result;
    }
    topic = topic.replace("{shadowName}", request.shadowName);
    Consumer<MqttMessage> messageHandler = (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            ErrorResponse response = gson.fromJson(payload, ErrorResponse.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    };
    return connection.subscribe(topic, qos, messageHandler);
}
Also used : UpdateShadowResponse(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowResponse) NamedShadowUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.NamedShadowUpdatedSubscriptionRequest) ShadowUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSubscriptionRequest) DeleteShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteShadowSubscriptionRequest) UpdateShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest) ShadowUpdatedEvent(software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedEvent) GetNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowRequest) HashMap(java.util.HashMap) EnumSerializer(software.amazon.awssdk.iot.EnumSerializer) CompletableFuture(java.util.concurrent.CompletableFuture) DeleteNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowSubscriptionRequest) GsonBuilder(com.google.gson.GsonBuilder) ByteBuffer(java.nio.ByteBuffer) NamedShadowDeltaUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.NamedShadowDeltaUpdatedSubscriptionRequest) ShadowState(software.amazon.awssdk.iot.iotshadow.model.ShadowState) ShadowUpdatedSnapshot(software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSnapshot) UpdateNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) ShadowMetadata(software.amazon.awssdk.iot.iotshadow.model.ShadowMetadata) Gson(com.google.gson.Gson) GetShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest) GetShadowResponse(software.amazon.awssdk.iot.iotshadow.model.GetShadowResponse) DeleteShadowRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteShadowRequest) ShadowStateWithDelta(software.amazon.awssdk.iot.iotshadow.model.ShadowStateWithDelta) DeleteNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowRequest) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ShadowDeltaUpdatedEvent(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedEvent) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ShadowDeltaUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest) StandardCharsets(java.nio.charset.StandardCharsets) GetShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest) Consumer(java.util.function.Consumer) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) Timestamp(software.amazon.awssdk.iot.Timestamp) ErrorResponse(software.amazon.awssdk.iot.iotshadow.model.ErrorResponse) ShadowStateFactory(software.amazon.awssdk.iot.ShadowStateFactory) DeleteShadowResponse(software.amazon.awssdk.iot.iotshadow.model.DeleteShadowResponse) GetNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UpdateShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowRequest) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ErrorResponse(software.amazon.awssdk.iot.iotshadow.model.ErrorResponse)

Example 4 with GetNamedShadowSubscriptionRequest

use of software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest in project aws-greengrass-nucleus by aws-greengrass.

the class ShadowDeploymentListener method subscribeToShadowTopics.

/*
        Subscribe to "$aws/things/{thingName}/shadow/update/accepted" topic to get notified when shadow is updated
        Subscribe to "$aws/things/{thingName}/shadow/update/rejected" topic to get notified when an update is rejected
        Subscribe to "$aws/things/{thingName}/shadow/get/accepted" topic to retrieve shadow by publishing to get topic
     */
private void subscribeToShadowTopics() {
    logger.atDebug().log(SUBSCRIBING_TO_SHADOW_TOPICS_MESSAGE);
    while (true) {
        try {
            UpdateNamedShadowSubscriptionRequest updateNamedShadowSubscriptionRequest = new UpdateNamedShadowSubscriptionRequest();
            updateNamedShadowSubscriptionRequest.shadowName = DEPLOYMENT_SHADOW_NAME;
            updateNamedShadowSubscriptionRequest.thingName = thingName;
            iotShadowClient.SubscribeToUpdateNamedShadowAccepted(updateNamedShadowSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, updateShadowResponse -> shadowUpdated(updateShadowResponse.state.desired, updateShadowResponse.state.reported, updateShadowResponse.version), (e) -> logger.atError().log("Error processing updateShadowResponse", e)).get(TIMEOUT_FOR_SUBSCRIBING_TO_TOPICS_SECONDS, TimeUnit.SECONDS);
            logger.debug("Subscribed to update named shadow accepted topic");
            iotShadowClient.SubscribeToUpdateNamedShadowRejected(updateNamedShadowSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, updateShadowRejected -> handleNamedShadowRejectedEvent(), (e) -> logger.atError().log("Error processing named shadow update rejected response", e)).get(TIMEOUT_FOR_SUBSCRIBING_TO_TOPICS_SECONDS, TimeUnit.SECONDS);
            logger.debug("Subscribed to update named shadow rejected topic");
            GetNamedShadowSubscriptionRequest getNamedShadowSubscriptionRequest = new GetNamedShadowSubscriptionRequest();
            getNamedShadowSubscriptionRequest.shadowName = DEPLOYMENT_SHADOW_NAME;
            getNamedShadowSubscriptionRequest.thingName = thingName;
            iotShadowClient.SubscribeToGetNamedShadowAccepted(getNamedShadowSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, getShadowResponse -> shadowUpdated(getShadowResponse.state.desired, getShadowResponse.state.reported, getShadowResponse.version), (e) -> logger.atError().log("Error processing getShadowResponse", e)).get(TIMEOUT_FOR_SUBSCRIBING_TO_TOPICS_SECONDS, TimeUnit.SECONDS);
            logger.debug("Subscribed to get named shadow topic");
            return;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof MqttException || cause instanceof TimeoutException) {
                logger.atWarn().setCause(cause).log("Caught exception while subscribing to shadow topics, " + "will retry shortly");
            } else if (cause instanceof InterruptedException) {
                logger.atWarn().log("Interrupted while subscribing to shadow topics");
                return;
            } else {
                logger.atError().setCause(e).log("Caught exception while subscribing to shadow topics, will retry shortly");
            }
        } catch (TimeoutException e) {
            logger.atWarn().setCause(e).log("Subscribe to shadow topics timed out, will retry shortly");
        } catch (InterruptedException e) {
            // Since this method can run as runnable cannot throw exception so handling exceptions here
            logger.atWarn().log("Interrupted while subscribing to shadow topics");
            return;
        }
        try {
            // Wait for sometime and then try to subscribe again
            Thread.sleep(WAIT_TIME_TO_SUBSCRIBE_AGAIN_IN_MS + JITTER.nextInt(10_000));
        } catch (InterruptedException interruptedException) {
            logger.atWarn().log("Interrupted while subscribing to device shadow topics");
            return;
        }
    }
}
Also used : GetNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowRequest) Deployment(com.aws.greengrass.deployment.model.Deployment) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) MqttClientConnectionEvents(software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents) UpdateNamedShadowRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) LogManager(com.aws.greengrass.logging.impl.LogManager) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) DEPLOYMENT_STATUS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_KEY_NAME) UUID(java.util.UUID) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) WrapperMqttClientConnection(com.aws.greengrass.mqttclient.WrapperMqttClientConnection) ARN_FOR_STATUS_KEY(com.aws.greengrass.status.DeploymentInformation.ARN_FOR_STATUS_KEY) FAILURE_CAUSE_KEY(com.aws.greengrass.status.StatusDetails.FAILURE_CAUSE_KEY) GetNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) DEPLOYMENT_DETAILED_STATUS_KEY(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_DETAILED_STATUS_KEY) DETAILED_STATUS_KEY(com.aws.greengrass.status.StatusDetails.DETAILED_STATUS_KEY) SerializerFactory(com.aws.greengrass.util.SerializerFactory) Setter(lombok.Setter) Getter(lombok.Getter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) STATUS_DETAILS_KEY(com.aws.greengrass.status.DeploymentInformation.STATUS_DETAILS_KEY) HashMap(java.util.HashMap) DEPLOYMENT_STATUS_DETAILS_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_STATUS_DETAILS_KEY_NAME) Configuration(com.amazon.aws.iot.greengrass.configuration.common.Configuration) Coerce(com.aws.greengrass.util.Coerce) AtomicReference(java.util.concurrent.atomic.AtomicReference) STATUS_KEY(com.aws.greengrass.status.DeploymentInformation.STATUS_KEY) ShadowState(software.amazon.awssdk.iot.iotshadow.model.ShadowState) Inject(javax.inject.Inject) GreengrassService(com.aws.greengrass.lifecyclemanager.GreengrassService) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) IotShadowClient(software.amazon.awssdk.iot.iotshadow.IotShadowClient) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) InjectionActions(com.aws.greengrass.dependency.InjectionActions) ExecutorService(java.util.concurrent.ExecutorService) ServiceLoadException(com.aws.greengrass.lifecyclemanager.exceptions.ServiceLoadException) DeploymentType(com.aws.greengrass.deployment.model.Deployment.DeploymentType) DEPLOYMENT_FAILURE_CAUSE_KEY(com.aws.greengrass.deployment.DeploymentService.DEPLOYMENT_FAILURE_CAUSE_KEY) DEPLOYMENT_ID_KEY_NAME(com.aws.greengrass.deployment.DeploymentStatusKeeper.DEPLOYMENT_ID_KEY_NAME) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) WhatHappened(com.aws.greengrass.config.WhatHappened) DeploymentTaskMetadata(com.aws.greengrass.deployment.model.DeploymentTaskMetadata) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) DeviceConfigurationException(com.aws.greengrass.deployment.exceptions.DeviceConfigurationException) MqttClient(com.aws.greengrass.mqttclient.MqttClient) Logger(com.aws.greengrass.logging.api.Logger) NoArgsConstructor(lombok.NoArgsConstructor) GetNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ExecutionException(java.util.concurrent.ExecutionException) UpdateNamedShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

HashMap (java.util.HashMap)4 Consumer (java.util.function.Consumer)3 QualityOfService (software.amazon.awssdk.crt.mqtt.QualityOfService)3 GetNamedShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest)3 ShadowState (software.amazon.awssdk.iot.iotshadow.model.ShadowState)3 UpdateNamedShadowRequest (software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest)3 UpdateNamedShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ByteBuffer (java.nio.ByteBuffer)2 StandardCharsets (java.nio.charset.StandardCharsets)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)2 MqttException (software.amazon.awssdk.crt.mqtt.MqttException)2 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)2 EnumSerializer (software.amazon.awssdk.iot.EnumSerializer)2 ShadowStateFactory (software.amazon.awssdk.iot.ShadowStateFactory)2 Timestamp (software.amazon.awssdk.iot.Timestamp)2 DeleteNamedShadowRequest (software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowRequest)2