Search in sources :

Example 1 with MqttException

use of software.amazon.awssdk.crt.mqtt.MqttException in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsClientWrapper method SubscribeToJobExecutionsChangedEvents.

@Override
public CompletableFuture<Integer> SubscribeToJobExecutionsChangedEvents(JobExecutionsChangedSubscriptionRequest request, QualityOfService qos, Consumer<JobExecutionsChangedEvent> handler, Consumer<Exception> exceptionHandler) {
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture();
        result.completeExceptionally(new MqttException("JobExecutionsChangedSubscriptionRequest must have a non-null thingName"));
        return result;
    }
    String topic = String.format(JOB_EXECUTIONS_CHANGED_TOPIC, request.thingName);
    Consumer<MqttMessage> messageHandler = jobExecutionCbs.computeIfAbsent(new Pair<>(handler, exceptionHandler), (k) -> (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            JobExecutionsChangedEvent response = this.gson.fromJson(payload, JobExecutionsChangedEvent.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    });
    return this.connection.subscribe(topic, qos, messageHandler);
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) JobExecutionsChangedEvent(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedEvent) MqttException(software.amazon.awssdk.crt.mqtt.MqttException)

Example 2 with MqttException

use of software.amazon.awssdk.crt.mqtt.MqttException in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsClientWrapper method SubscribeToDescribeJobExecutionAccepted.

@Override
public CompletableFuture<Integer> SubscribeToDescribeJobExecutionAccepted(DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<DescribeJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) {
    if (request.jobId == null || request.thingName == null) {
        CompletableFuture result = new CompletableFuture();
        result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null jobId and a non-null thingName"));
        return result;
    }
    String topic = String.format(JOB_DESCRIBE_ACCEPTED_TOPIC, request.thingName, request.jobId);
    Consumer<MqttMessage> messageHandler = describeJobCbs.computeIfAbsent(new Pair<>(handler, exceptionHandler), (k) -> (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            DescribeJobExecutionResponse response = this.gson.fromJson(payload, DescribeJobExecutionResponse.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    });
    return this.connection.subscribe(topic, qos, messageHandler);
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) DescribeJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionResponse) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException)

Example 3 with MqttException

use of software.amazon.awssdk.crt.mqtt.MqttException in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsHelper method subscribeToEventNotifications.

/**
 * Subscribe to $aws/things/{thingName}/jobs/notify topic.
 *
 * @param eventHandler The handler which run when an event is received
 * @throws ExecutionException   When subscribe failed with an exception
 * @throws InterruptedException When this thread was interrupted
 * @throws TimeoutException     if the operation does not complete within the given time
 */
protected void subscribeToEventNotifications(Consumer<JobExecutionsChangedEvent> eventHandler) throws InterruptedException {
    logger.atDebug().log("Subscribing to deployment job event notifications.");
    JobExecutionsChangedSubscriptionRequest request = new JobExecutionsChangedSubscriptionRequest();
    request.thingName = this.thingName;
    while (true) {
        CompletableFuture<Integer> subscribed = iotJobsClientWrapper.SubscribeToJobExecutionsChangedEvents(request, QualityOfService.AT_LEAST_ONCE, eventHandler);
        try {
            subscribed.get(mqttClient.getMqttOperationTimeoutMillis(), TimeUnit.MILLISECONDS);
            logger.atDebug().log("Subscribed to deployment job event notifications.");
            break;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof MqttException || cause instanceof TimeoutException) {
                logger.atWarn().setCause(cause).log(SUBSCRIPTION_EVENT_NOTIFICATIONS_RETRY);
            }
            if (cause instanceof InterruptedException) {
                logger.atWarn().log(SUBSCRIPTION_EVENT_NOTIFICATIONS_INTERRUPTED);
                break;
            }
        } catch (InterruptedException e) {
            logger.atWarn().log(SUBSCRIPTION_EVENT_NOTIFICATIONS_INTERRUPTED);
            throw e;
        } catch (TimeoutException e) {
            logger.atWarn().setCause(e).log(SUBSCRIPTION_EVENT_NOTIFICATIONS_RETRY);
        }
        try {
            // Wait for sometime and then try to subscribe again
            Thread.sleep(waitTimeToSubscribeAgain + RANDOM.nextInt(10_000));
        } catch (InterruptedException interruptedException) {
            logger.atWarn().log(SUBSCRIPTION_EVENT_NOTIFICATIONS_INTERRUPTED);
            break;
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JobExecutionsChangedSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with MqttException

use of software.amazon.awssdk.crt.mqtt.MqttException in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsHelper method subscribeToGetNextJobDescription.

/**
 * Subscribes to the describe job topic to get the job details for the next available pending job
 * It also publishes a message to get the next pending job.
 * It returns an empty message if nothing is available
 *
 * @param consumerAccept Consumer for when the job is accepted
 * @param consumerReject Consumer for when the job is rejected
 * @throws ExecutionException   if subscribing fails
 * @throws InterruptedException if the thread gets interrupted
 * @throws TimeoutException     if the operation does not complete within the given time
 */
protected void subscribeToGetNextJobDescription(Consumer<DescribeJobExecutionResponse> consumerAccept, Consumer<RejectedError> consumerReject) throws InterruptedException {
    logger.atDebug().log("Subscribing to deployment job execution update.");
    DescribeJobExecutionSubscriptionRequest describeJobExecutionSubscriptionRequest = new DescribeJobExecutionSubscriptionRequest();
    describeJobExecutionSubscriptionRequest.thingName = this.thingName;
    describeJobExecutionSubscriptionRequest.jobId = NEXT_JOB_LITERAL;
    while (true) {
        CompletableFuture<Integer> subscribed = iotJobsClientWrapper.SubscribeToDescribeJobExecutionAccepted(describeJobExecutionSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, consumerAccept);
        try {
            subscribed.get(mqttClient.getMqttOperationTimeoutMillis(), TimeUnit.MILLISECONDS);
            subscribed = iotJobsClientWrapper.SubscribeToDescribeJobExecutionRejected(describeJobExecutionSubscriptionRequest, QualityOfService.AT_LEAST_ONCE, consumerReject);
            subscribed.get(mqttClient.getMqttOperationTimeoutMillis(), TimeUnit.MILLISECONDS);
            logger.atDebug().log("Subscribed to deployment job execution update.");
            break;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof MqttException || cause instanceof TimeoutException) {
                logger.atWarn().setCause(cause).log(SUBSCRIPTION_JOB_DESCRIPTION_RETRY_MESSAGE);
            }
            if (cause instanceof InterruptedException) {
                logger.atWarn().log(SUBSCRIPTION_JOB_DESCRIPTION_INTERRUPTED);
                break;
            }
        } catch (TimeoutException e) {
            logger.atWarn().setCause(e).log(SUBSCRIPTION_JOB_DESCRIPTION_RETRY_MESSAGE);
        } catch (InterruptedException e) {
            logger.atWarn().log(SUBSCRIPTION_JOB_DESCRIPTION_INTERRUPTED);
            throw e;
        }
        try {
            // Wait for sometime and then try to subscribe again
            Thread.sleep(waitTimeToSubscribeAgain + RANDOM.nextInt(10_000));
        } catch (InterruptedException interruptedException) {
            logger.atWarn().log(SUBSCRIPTION_JOB_DESCRIPTION_INTERRUPTED);
            break;
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ExecutionException(java.util.concurrent.ExecutionException) DescribeJobExecutionSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionSubscriptionRequest) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with MqttException

use of software.amazon.awssdk.crt.mqtt.MqttException in project aws-iot-device-sdk-java-v2 by aws.

the class IotShadowClient method PublishDeleteNamedShadow.

/**
 * Deletes a named shadow for an AWS IoT thing.
 *
 * If the device is offline, the PUBLISH packet will be sent once the connection resumes.
 *
 * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-mqtt.html#delete-pub-sub-topic
 *
 * @param request Message to be serialized and sent
 * @param qos Quality of Service for delivering this message
 * @return a future containing the MQTT packet id used to perform the publish operation
 *
 * * For QoS 0, completes as soon as the packet is sent.
 * * For QoS 1, completes when PUBACK is received.
 * * QoS 2 is not supported by AWS IoT.
 */
public CompletableFuture<Integer> PublishDeleteNamedShadow(DeleteNamedShadowRequest request, QualityOfService qos) {
    String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/delete";
    if (request.shadowName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("DeleteNamedShadowRequest must have a non-null shadowName"));
        return result;
    }
    topic = topic.replace("{shadowName}", request.shadowName);
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("DeleteNamedShadowRequest must have a non-null thingName"));
        return result;
    }
    topic = topic.replace("{thingName}", request.thingName);
    String payloadJson = gson.toJson(request);
    MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8));
    return connection.publish(message, qos, false);
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) MqttException(software.amazon.awssdk.crt.mqtt.MqttException)

Aggregations

MqttException (software.amazon.awssdk.crt.mqtt.MqttException)52 CompletableFuture (java.util.concurrent.CompletableFuture)48 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)46 Consumer (java.util.function.Consumer)29 MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)29 QualityOfService (software.amazon.awssdk.crt.mqtt.QualityOfService)29 Gson (com.google.gson.Gson)28 GsonBuilder (com.google.gson.GsonBuilder)28 UnsupportedEncodingException (java.io.UnsupportedEncodingException)28 ByteBuffer (java.nio.ByteBuffer)28 StandardCharsets (java.nio.charset.StandardCharsets)28 EnumSerializer (software.amazon.awssdk.iot.EnumSerializer)28 Timestamp (software.amazon.awssdk.iot.Timestamp)28 HashMap (java.util.HashMap)27 GetNamedShadowRequest (software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowRequest)17 GetNamedShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest)17 ShadowState (software.amazon.awssdk.iot.iotshadow.model.ShadowState)17 UpdateNamedShadowRequest (software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest)17 UpdateNamedShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest)17 ShadowStateFactory (software.amazon.awssdk.iot.ShadowStateFactory)16