Search in sources :

Example 1 with SubscribeToIoTCoreRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest in project aws-iot-greengrass-edge-connector-for-kinesis-video-stream by awslabs.

the class VideoUploadRequestHandler method subscribeToMqttTopic.

/**
 * Subscribes to Specified MQTT Topic for Video Upload Request Events.
 *
 * @param mqttTopic - Name of the MQTT topic where video upload request will be sent
 * @param event     - Callback event for onStart or onError
 */
public void subscribeToMqttTopic(String mqttTopic, VideoUploadRequestEvent event) {
    StreamResponseHandler<IoTCoreMessage> streamResponseHandler;
    streamResponseHandler = new StreamResponseHandler<IoTCoreMessage>() {

        @Override
        public void onStreamEvent(IoTCoreMessage ioTCoreMessage) {
            log.info("onStreamEvent");
            MQTTMessage mqttMessage = ioTCoreMessage.getMessage();
            if (mqttMessage == null) {
                log.error("Empty MQTT Message Received");
                return;
            }
            String payload = new String(mqttMessage.getPayload(), StandardCharsets.UTF_8);
            VideoUploadRequestMessage videoUploadRequestMessage = JSONUtils.jsonToVideoUplaodRequestMessage(payload);
            List<AssetPropertyValue> propertyValueEntry = videoUploadRequestMessage.getPayload().getValues();
            if (propertyValueEntry.size() == 1) {
                AssetPropertyValue assetPropertyValue = propertyValueEntry.get(0);
                long propertyUpdateTimestamp = assetPropertyValue.timestamp().timeInSeconds();
                String value = assetPropertyValue.value().stringValue();
                long startTimestamp = 0;
                long endTimestamp = 0;
                boolean isLive = false;
                if (value.equalsIgnoreCase(MQTT_LIVE_VIDEO_UPLOAD_REQUEST_KEY)) {
                    // Live Uploading Request
                    isLive = true;
                    log.info("Live Streaming Request Received");
                } else {
                    // On-Demand Video Uploading Request
                    String[] timestamps = value.split("-");
                    if (timestamps.length == 2) {
                        try {
                            startTimestamp = Long.parseLong(timestamps[0]);
                            endTimestamp = Long.parseLong(timestamps[1]);
                            log.info("On-Demand Streaming Request Received for Time Range " + timestamps[0] + "-" + timestamps[1]);
                        } catch (NumberFormatException ex) {
                            log.error("Invalid VideoUploadRequest Event Received. " + ex.getMessage());
                        }
                    } else {
                        log.error("Invalid VideoUploadRequest Event Received. Single hyphen required");
                    }
                }
                event.onStart(isLive, propertyUpdateTimestamp, startTimestamp, endTimestamp);
            } else {
                log.error("Invalid VideoUploadRequest Event Received. Single value required");
            }
        }

        @Override
        public boolean onStreamError(Throwable throwable) {
            log.info("onStream Error: " + throwable.getMessage());
            event.onError(throwable.getMessage());
            // Handle error.
            return false;
        }

        @Override
        public void onStreamClosed() {
            log.info("onStream Closed Called");
        }
    };
    try {
        SubscribeToIoTCoreRequest subscribeToIoTCoreRequest = new SubscribeToIoTCoreRequest();
        subscribeToIoTCoreRequest.setTopicName(mqttTopic);
        subscribeToIoTCoreRequest.setQos(QOS.AT_MOST_ONCE);
        SubscribeToIoTCoreResponseHandler operationResponseHandler = greengrassCoreIPCClient.subscribeToIoTCore(subscribeToIoTCoreRequest, Optional.of(streamResponseHandler));
        SubscribeToIoTCoreResponse resp = operationResponseHandler.getResponse().get();
        log.info("Subscribe to MQTT Response: " + resp.toString());
    } catch (ExecutionException ex) {
        final String errorMessage = String.format("Could not Subscribe to MQTT topic %s. %s", mqttTopic, ex.getMessage());
        log.error(errorMessage);
        throw new EdgeConnectorForKVSException(errorMessage, ex);
    } catch (InterruptedException ex) {
        final String errorMessage = String.format("Could not Subscribe to MQTT topic %s. %s", mqttTopic, ex.getMessage());
        log.error(errorMessage);
        // restore interrupted state
        Thread.currentThread().interrupt();
        throw new EdgeConnectorForKVSException(errorMessage, ex);
    }
}
Also used : VideoUploadRequestMessage(com.aws.iot.edgeconnectorforkvs.model.VideoUploadRequestMessage) EdgeConnectorForKVSException(com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException) MQTTMessage(software.amazon.awssdk.aws.greengrass.model.MQTTMessage) SubscribeToIoTCoreResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreResponse) IoTCoreMessage(software.amazon.awssdk.aws.greengrass.model.IoTCoreMessage) AssetPropertyValue(software.amazon.awssdk.services.iotsitewise.model.AssetPropertyValue) SubscribeToIoTCoreRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest) SubscribeToIoTCoreResponseHandler(software.amazon.awssdk.aws.greengrass.SubscribeToIoTCoreResponseHandler) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with SubscribeToIoTCoreRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest in project aws-greengrass-nucleus by aws-greengrass.

the class MqttProxyIPCAgentTest method GIVEN_MqttProxyIPCAgent_WHEN_subscribe_with_invalid_qos_THEN_error_thrown.

@Test
void GIVEN_MqttProxyIPCAgent_WHEN_subscribe_with_invalid_qos_THEN_error_thrown() throws Exception {
    SubscribeToIoTCoreRequest subscribeToIoTCoreRequest = new SubscribeToIoTCoreRequest();
    subscribeToIoTCoreRequest.setTopicName(TEST_TOPIC);
    subscribeToIoTCoreRequest.setQos("10");
    when(authorizationHandler.isAuthorized(any(), any(), any())).thenReturn(true);
    try (MqttProxyIPCAgent.SubscribeToIoTCoreOperationHandler subscribeToIoTCoreOperationHandler = mqttProxyIPCAgent.getSubscribeToIoTCoreOperationHandler(mockContext)) {
        assertThrows(InvalidArgumentsError.class, () -> {
            subscribeToIoTCoreOperationHandler.handleRequest(subscribeToIoTCoreRequest);
        });
    }
}
Also used : SubscribeToIoTCoreRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest) Test(org.junit.jupiter.api.Test)

Example 3 with SubscribeToIoTCoreRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest in project aws-greengrass-nucleus by aws-greengrass.

the class MqttProxyIPCAgentTest method GIVEN_MqttProxyIPCAgent_WHEN_subscribe_with_no_qos_THEN_error_thrown.

@Test
void GIVEN_MqttProxyIPCAgent_WHEN_subscribe_with_no_qos_THEN_error_thrown() throws Exception {
    SubscribeToIoTCoreRequest subscribeToIoTCoreRequest = new SubscribeToIoTCoreRequest();
    subscribeToIoTCoreRequest.setTopicName(TEST_TOPIC);
    when(authorizationHandler.isAuthorized(any(), any(), any())).thenReturn(true);
    try (MqttProxyIPCAgent.SubscribeToIoTCoreOperationHandler subscribeToIoTCoreOperationHandler = mqttProxyIPCAgent.getSubscribeToIoTCoreOperationHandler(mockContext)) {
        assertThrows(InvalidArgumentsError.class, () -> {
            subscribeToIoTCoreOperationHandler.handleRequest(subscribeToIoTCoreRequest);
        });
    }
}
Also used : SubscribeToIoTCoreRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest) Test(org.junit.jupiter.api.Test)

Example 4 with SubscribeToIoTCoreRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest in project aws-greengrass-nucleus by aws-greengrass.

the class MqttProxyIPCAgentTest method GIVEN_MqttProxyIPCAgent_WHEN_subscribe_to_topic_THEN_topic_subscribed.

@Test
void GIVEN_MqttProxyIPCAgent_WHEN_subscribe_to_topic_THEN_topic_subscribed() throws Exception {
    SubscribeToIoTCoreRequest subscribeToIoTCoreRequest = new SubscribeToIoTCoreRequest();
    subscribeToIoTCoreRequest.setTopicName(TEST_TOPIC);
    subscribeToIoTCoreRequest.setQos(QOS.AT_LEAST_ONCE);
    when(authorizationHandler.isAuthorized(any(), any(), any())).thenReturn(true);
    ArgumentCaptor<SubscribeRequest> subscribeRequestArgumentCaptor = ArgumentCaptor.forClass(SubscribeRequest.class);
    ArgumentCaptor<UnsubscribeRequest> unsubscribeRequestArgumentCaptor = ArgumentCaptor.forClass(UnsubscribeRequest.class);
    ArgumentCaptor<IoTCoreMessage> ioTCoreMessageArgumentCaptor = ArgumentCaptor.forClass(IoTCoreMessage.class);
    try (MqttProxyIPCAgent.SubscribeToIoTCoreOperationHandler subscribeToIoTCoreOperationHandler = spy(mqttProxyIPCAgent.getSubscribeToIoTCoreOperationHandler(mockContext))) {
        SubscribeToIoTCoreResponse subscribeToIoTCoreResponse = subscribeToIoTCoreOperationHandler.handleRequest(subscribeToIoTCoreRequest);
        assertNotNull(subscribeToIoTCoreResponse);
        verify(authorizationHandler).isAuthorized(MQTT_PROXY_SERVICE_NAME, Permission.builder().principal(TEST_SERVICE).operation(GreengrassCoreIPCService.SUBSCRIBE_TO_IOT_CORE).resource(TEST_TOPIC).build(), ResourceLookupPolicy.MQTT_STYLE);
        verify(mqttClient).subscribe(subscribeRequestArgumentCaptor.capture());
        SubscribeRequest capturedSubscribeRequest = subscribeRequestArgumentCaptor.getValue();
        assertThat(capturedSubscribeRequest.getTopic(), is(TEST_TOPIC));
        assertThat(capturedSubscribeRequest.getQos(), is(QualityOfService.AT_LEAST_ONCE));
        Consumer<MqttMessage> callback = capturedSubscribeRequest.getCallback();
        MqttMessage message = new MqttMessage(TEST_TOPIC, TEST_PAYLOAD);
        doReturn(new CompletableFuture<>()).when(subscribeToIoTCoreOperationHandler).sendStreamEvent(any());
        callback.accept(message);
        verify(subscribeToIoTCoreOperationHandler).sendStreamEvent(ioTCoreMessageArgumentCaptor.capture());
        MQTTMessage mqttMessage = ioTCoreMessageArgumentCaptor.getValue().getMessage();
        assertThat(mqttMessage.getPayload(), is(TEST_PAYLOAD));
        assertThat(mqttMessage.getTopicName(), is(TEST_TOPIC));
        subscribeToIoTCoreOperationHandler.onStreamClosed();
        verify(mqttClient).unsubscribe(unsubscribeRequestArgumentCaptor.capture());
        UnsubscribeRequest capturedUnsubscribedRequest = unsubscribeRequestArgumentCaptor.getValue();
        assertThat(capturedUnsubscribedRequest.getTopic(), is(TEST_TOPIC));
        assertThat(capturedUnsubscribedRequest.getCallback(), is(callback));
    }
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) MQTTMessage(software.amazon.awssdk.aws.greengrass.model.MQTTMessage) SubscribeToIoTCoreResponse(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreResponse) IoTCoreMessage(software.amazon.awssdk.aws.greengrass.model.IoTCoreMessage) UnsubscribeRequest(com.aws.greengrass.mqttclient.UnsubscribeRequest) SubscribeToIoTCoreRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest) SubscribeRequest(com.aws.greengrass.mqttclient.SubscribeRequest) Test(org.junit.jupiter.api.Test)

Example 5 with SubscribeToIoTCoreRequest

use of software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest in project aws-greengrass-nucleus by aws-greengrass.

the class MqttProxyIPCAgentTest method GIVEN_MqttProxyIPCAgent_WHEN_subscribe_with_no_topic_THEN_error_thrown.

@Test
void GIVEN_MqttProxyIPCAgent_WHEN_subscribe_with_no_topic_THEN_error_thrown() throws Exception {
    SubscribeToIoTCoreRequest subscribeToIoTCoreRequest = new SubscribeToIoTCoreRequest();
    subscribeToIoTCoreRequest.setQos(QOS.AT_LEAST_ONCE);
    try (MqttProxyIPCAgent.SubscribeToIoTCoreOperationHandler subscribeToIoTCoreOperationHandler = mqttProxyIPCAgent.getSubscribeToIoTCoreOperationHandler(mockContext)) {
        assertThrows(InvalidArgumentsError.class, () -> {
            subscribeToIoTCoreOperationHandler.handleRequest(subscribeToIoTCoreRequest);
        });
    }
}
Also used : SubscribeToIoTCoreRequest(software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest) Test(org.junit.jupiter.api.Test)

Aggregations

SubscribeToIoTCoreRequest (software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest)6 Test (org.junit.jupiter.api.Test)5 IoTCoreMessage (software.amazon.awssdk.aws.greengrass.model.IoTCoreMessage)3 SubscribeRequest (com.aws.greengrass.mqttclient.SubscribeRequest)2 UnsubscribeRequest (com.aws.greengrass.mqttclient.UnsubscribeRequest)2 SubscribeToIoTCoreResponseHandler (software.amazon.awssdk.aws.greengrass.SubscribeToIoTCoreResponseHandler)2 MQTTMessage (software.amazon.awssdk.aws.greengrass.model.MQTTMessage)2 SubscribeToIoTCoreResponse (software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreResponse)2 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)2 VideoUploadRequestMessage (com.aws.iot.edgeconnectorforkvs.model.VideoUploadRequestMessage)1 EdgeConnectorForKVSException (com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException)1 List (java.util.List)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutionException (java.util.concurrent.ExecutionException)1 GreengrassCoreIPCClient (software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClient)1 StreamResponseHandler (software.amazon.awssdk.eventstreamrpc.StreamResponseHandler)1 AssetPropertyValue (software.amazon.awssdk.services.iotsitewise.model.AssetPropertyValue)1