Search in sources :

Example 1 with ShadowDeltaUpdatedSubscriptionRequest

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

the class ShadowSample method main.

public static void main(String[] args) {
    cmdUtils = new CommandLineUtils();
    cmdUtils.registerProgramName("ShadowSample");
    cmdUtils.addCommonMQTTCommands();
    cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
    cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
    cmdUtils.registerCommand("port", "<int>", "Port to use (optional, default='8883').");
    cmdUtils.registerCommand("thing_name", "<str>", "The name of the IoT thing.");
    cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*')");
    cmdUtils.sendArguments(args);
    thingName = cmdUtils.getCommandRequired("thing_name", "");
    MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {

        @Override
        public void onConnectionInterrupted(int errorCode) {
            if (errorCode != 0) {
                System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
            }
        }

        @Override
        public void onConnectionResumed(boolean sessionPresent) {
            System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
        }
    };
    try {
        MqttClientConnection connection = cmdUtils.buildMQTTConnection(callbacks);
        shadow = new IotShadowClient(connection);
        CompletableFuture<Boolean> connected = connection.connect();
        try {
            boolean sessionPresent = connected.get();
            System.out.println("Connected to " + (!sessionPresent ? "clean" : "existing") + " session!");
        } catch (Exception ex) {
            throw new RuntimeException("Exception occurred during connect", ex);
        }
        System.out.println("Subscribing to shadow delta events...");
        ShadowDeltaUpdatedSubscriptionRequest requestShadowDeltaUpdated = new ShadowDeltaUpdatedSubscriptionRequest();
        requestShadowDeltaUpdated.thingName = thingName;
        CompletableFuture<Integer> subscribedToDeltas = shadow.SubscribeToShadowDeltaUpdatedEvents(requestShadowDeltaUpdated, QualityOfService.AT_LEAST_ONCE, ShadowSample::onShadowDeltaUpdated);
        subscribedToDeltas.get();
        System.out.println("Subscribing to update respones...");
        UpdateShadowSubscriptionRequest requestUpdateShadow = new UpdateShadowSubscriptionRequest();
        requestUpdateShadow.thingName = thingName;
        CompletableFuture<Integer> subscribedToUpdateAccepted = shadow.SubscribeToUpdateShadowAccepted(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowAccepted);
        CompletableFuture<Integer> subscribedToUpdateRejected = shadow.SubscribeToUpdateShadowRejected(requestUpdateShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onUpdateShadowRejected);
        subscribedToUpdateAccepted.get();
        subscribedToUpdateRejected.get();
        System.out.println("Subscribing to get responses...");
        GetShadowSubscriptionRequest requestGetShadow = new GetShadowSubscriptionRequest();
        requestGetShadow.thingName = thingName;
        CompletableFuture<Integer> subscribedToGetShadowAccepted = shadow.SubscribeToGetShadowAccepted(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowAccepted);
        CompletableFuture<Integer> subscribedToGetShadowRejected = shadow.SubscribeToGetShadowRejected(requestGetShadow, QualityOfService.AT_LEAST_ONCE, ShadowSample::onGetShadowRejected);
        subscribedToGetShadowAccepted.get();
        subscribedToGetShadowRejected.get();
        gotResponse = new CompletableFuture<>();
        System.out.println("Requesting current shadow state...");
        GetShadowRequest getShadowRequest = new GetShadowRequest();
        getShadowRequest.thingName = thingName;
        CompletableFuture<Integer> publishedGetShadow = shadow.PublishGetShadow(getShadowRequest, QualityOfService.AT_LEAST_ONCE);
        publishedGetShadow.get();
        gotResponse.get();
        String newValue = "";
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print(SHADOW_PROPERTY + "> ");
            System.out.flush();
            newValue = scanner.next();
            if (newValue.compareToIgnoreCase("quit") == 0) {
                break;
            }
            gotResponse = new CompletableFuture<>();
            changeShadowValue(newValue).get();
            gotResponse.get();
        }
        scanner.close();
        CompletableFuture<Void> disconnected = connection.disconnect();
        disconnected.get();
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        System.out.println("Exception encountered: " + ex.toString());
    }
    System.out.println("Complete!");
    CrtResource.waitForNoResources();
}
Also used : Scanner(java.util.Scanner) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) MqttClientConnectionEvents(software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents) UpdateShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest) IotShadowClient(software.amazon.awssdk.iot.iotshadow.IotShadowClient) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) GetShadowSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest) CommandLineUtils(utils.commandlineutils.CommandLineUtils) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) GetShadowRequest(software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest) ExecutionException(java.util.concurrent.ExecutionException) ShadowDeltaUpdatedSubscriptionRequest(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest) ExecutionException(java.util.concurrent.ExecutionException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException)

Example 2 with ShadowDeltaUpdatedSubscriptionRequest

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

the class IotShadowClient method SubscribeToShadowDeltaUpdatedEvents.

/**
 * Subscribe to ShadowDelta events for the (classic) shadow of an AWS IoT thing.
 *
 * 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#update-delta-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> SubscribeToShadowDeltaUpdatedEvents(ShadowDeltaUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowDeltaUpdatedEvent> handler, Consumer<Exception> exceptionHandler) {
    String topic = "$aws/things/{thingName}/shadow/update/delta";
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("ShadowDeltaUpdatedSubscriptionRequest must have a non-null thingName"));
        return result;
    }
    topic = topic.replace("{thingName}", request.thingName);
    Consumer<MqttMessage> messageHandler = (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            ShadowDeltaUpdatedEvent response = gson.fromJson(payload, ShadowDeltaUpdatedEvent.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) ShadowDeltaUpdatedEvent(software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedEvent) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)2 GetShadowRequest (software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest)2 GetShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest)2 ShadowDeltaUpdatedSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest)2 UpdateShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ByteBuffer (java.nio.ByteBuffer)1 StandardCharsets (java.nio.charset.StandardCharsets)1 HashMap (java.util.HashMap)1 Scanner (java.util.Scanner)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1 Consumer (java.util.function.Consumer)1 CrtRuntimeException (software.amazon.awssdk.crt.CrtRuntimeException)1 MqttClientConnectionEvents (software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents)1 MqttException (software.amazon.awssdk.crt.mqtt.MqttException)1 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)1 QualityOfService (software.amazon.awssdk.crt.mqtt.QualityOfService)1