Search in sources :

Example 6 with MqttMessage

use of software.amazon.awssdk.crt.mqtt.MqttMessage in project aws-crt-java by awslabs.

the class SelfPubSubTest method testPubSub.

@Test
public void testPubSub() {
    skipIfNetworkUnavailable();
    connect();
    try {
        CompletableFuture<MqttMessage> receivedFuture = new CompletableFuture<>();
        Consumer<MqttMessage> messageHandler = (message) -> {
            receivedFuture.complete(message);
        };
        CompletableFuture<Integer> subscribed = connection.subscribe(TEST_TOPIC, QualityOfService.AT_LEAST_ONCE, messageHandler);
        subscribed.thenApply(unused -> subsAcked++);
        int packetId = subscribed.get();
        assertNotSame(0, packetId);
        assertEquals("Single subscription", 1, subsAcked);
        MqttMessage message = new MqttMessage(TEST_TOPIC, TEST_PAYLOAD.getBytes(), QualityOfService.AT_LEAST_ONCE, false);
        CompletableFuture<Integer> published = connection.publish(message);
        published.thenApply(unused -> pubsAcked++);
        packetId = published.get();
        assertNotSame(0, packetId);
        assertEquals("Published", 1, pubsAcked);
        published = connection.publish(message);
        published.thenApply(unused -> pubsAcked++);
        packetId = published.get();
        assertNotSame(0, packetId);
        assertEquals("Published", 2, pubsAcked);
        MqttMessage received = receivedFuture.get();
        assertEquals("Received", message.getTopic(), received.getTopic());
        assertArrayEquals("Received", message.getPayload(), received.getPayload());
        assertEquals("Received", message.getQos(), received.getQos());
        assertEquals("Received", message.getRetain(), received.getRetain());
        CompletableFuture<Integer> unsubscribed = connection.unsubscribe(TEST_TOPIC);
        unsubscribed.thenApply(unused -> subsAcked--);
        packetId = unsubscribed.get();
        assertNotSame(0, packetId);
        assertEquals("No Subscriptions", 0, subsAcked);
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
    disconnect();
    close();
}
Also used : Assert.assertNotSame(org.junit.Assert.assertNotSame) Test(org.junit.Test) CompletableFuture(java.util.concurrent.CompletableFuture) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) Rule(org.junit.Rule) CrtResource(software.amazon.awssdk.crt.CrtResource) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) Timeout(org.junit.rules.Timeout) Assume(org.junit.Assume) Assert.fail(org.junit.Assert.fail) java.util.function(java.util.function) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Assert.assertEquals(org.junit.Assert.assertEquals) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Test(org.junit.Test)

Example 7 with MqttMessage

use of software.amazon.awssdk.crt.mqtt.MqttMessage in project aws-crt-java by awslabs.

the class WillTest method testWill.

@Test
public void testWill() {
    skipIfNetworkUnavailable();
    setConnectionConfigTransformer((config) -> {
        config.setWillMessage(new MqttMessage(TEST_TOPIC, TEST_WILL.getBytes(), QualityOfService.AT_LEAST_ONCE));
    });
    connect();
    disconnect();
    close();
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) Test(org.junit.Test)

Example 8 with MqttMessage

use of software.amazon.awssdk.crt.mqtt.MqttMessage in project aws-crt-java by awslabs.

the class WillTest method testEmptyWill.

@Test
public void testEmptyWill() {
    skipIfNetworkUnavailable();
    setConnectionConfigTransformer((config) -> {
        config.setWillMessage(new MqttMessage(TEST_TOPIC, TEST_EMPTY_WILL.getBytes(), QualityOfService.AT_LEAST_ONCE));
    });
    connect();
    disconnect();
    close();
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) Test(org.junit.Test)

Example 9 with MqttMessage

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

the class MQTTPublish method main.

public static void main(String[] args) {
    if (!DATestUtils.init(DATestUtils.TestType.SUB_PUB)) {
        throw new RuntimeException("Failed to initialize environment variables.");
    }
    try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) {
        builder.withClientId(clientId).withEndpoint(DATestUtils.endpoint).withPort((short) port).withCleanSession(true).withPingTimeoutMs(60000).withProtocolOperationTimeoutMs(60000);
        try (MqttClientConnection connection = builder.build()) {
            CompletableFuture<Boolean> connected = connection.connect();
            try {
                boolean sessionPresent = connected.get();
            } catch (Exception ex) {
                throw new RuntimeException("Exception occurred during connect", ex);
            }
            CompletableFuture<Integer> published = connection.publish(new MqttMessage(DATestUtils.topic, message.getBytes(), QualityOfService.AT_MOST_ONCE, false));
            published.get();
            Thread.sleep(1000);
            CompletableFuture<Void> disconnected = connection.disconnect();
            disconnected.get();
        }
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        onApplicationFailure(ex);
    }
    System.exit(0);
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) ExecutionException(java.util.concurrent.ExecutionException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) AwsIotMqttConnectionBuilder(software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Example 10 with MqttMessage

use of software.amazon.awssdk.crt.mqtt.MqttMessage 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

MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)62 CompletableFuture (java.util.concurrent.CompletableFuture)53 MqttException (software.amazon.awssdk.crt.mqtt.MqttException)46 MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)34 QualityOfService (software.amazon.awssdk.crt.mqtt.QualityOfService)33 UnsupportedEncodingException (java.io.UnsupportedEncodingException)31 StandardCharsets (java.nio.charset.StandardCharsets)31 Consumer (java.util.function.Consumer)31 Gson (com.google.gson.Gson)28 GsonBuilder (com.google.gson.GsonBuilder)28 ByteBuffer (java.nio.ByteBuffer)28 EnumSerializer (software.amazon.awssdk.iot.EnumSerializer)28 Timestamp (software.amazon.awssdk.iot.Timestamp)28 HashMap (java.util.HashMap)26 ShadowStateFactory (software.amazon.awssdk.iot.ShadowStateFactory)16 DeleteNamedShadowRequest (software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowRequest)16 DeleteNamedShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowSubscriptionRequest)16 DeleteShadowRequest (software.amazon.awssdk.iot.iotshadow.model.DeleteShadowRequest)16 DeleteShadowResponse (software.amazon.awssdk.iot.iotshadow.model.DeleteShadowResponse)16 DeleteShadowSubscriptionRequest (software.amazon.awssdk.iot.iotshadow.model.DeleteShadowSubscriptionRequest)16