Search in sources :

Example 1 with EdgeConnectorForKVSException

use of com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException in project aws-iot-greengrass-edge-connector-for-kinesis-video-stream by awslabs.

the class DiskManager method initDiskManager.

/**
 * Method to initialize local cached video file records.
 * The method all walk all given dir paths, generate Map, key is directoryPath, value is the
 * ConcurrentLinkedQueue which contains all existing video files.
 * @throws EdgeConnectorForKVSException - EdgeConnectorForKVS generic exception
 */
public void initDiskManager() throws EdgeConnectorForKVSException {
    diskManagerUtil.buildEdgeConnectorForKVSConfigurationMap(edgeConnectorForKVSConfigurationList);
    edgeConnectorForKVSConfigurationList.forEach(configuration -> {
        try {
            // Walk and build the existing records queue from existing recorded files
            diskManagerUtil.buildRecordedFilesMap(configuration);
        } catch (IOException e) {
            System.out.println(String.format("Fail to initialize recorded file map for path %s", configuration.getVideoRecordFolderPath().toString()));
            throw new EdgeConnectorForKVSException(e);
        }
    });
}
Also used : EdgeConnectorForKVSException(com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException) IOException(java.io.IOException)

Example 2 with EdgeConnectorForKVSException

use of com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException 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 3 with EdgeConnectorForKVSException

use of com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException in project aws-iot-greengrass-edge-connector-for-kinesis-video-stream by awslabs.

the class DiskManagerTest method testWatchService_File_Monitor_Thread_Exists_Case.

@Test
public void testWatchService_File_Monitor_Thread_Exists_Case(@TempDir Path tempDir) throws InterruptedException, IOException {
    // when
    List<EdgeConnectorForKVSConfiguration> edgeConnectorForKVSConfigurationList = Collections.singletonList(EdgeConnectorForKVSConfiguration.builder().videoRecordFolderPath(Paths.get("NonExistentFile.txt")).localDataRetentionPeriodInMinutes(LOCAL_DATA_RETENTION_PERIOD_IN_MINUTES).build());
    List<WatchEvent<?>> events = new ArrayList<>();
    testWatchEventCallBack = new TestWatchEventCallBack(events);
    diskManager = new DiskManager(edgeConnectorForKVSConfigurationList, diskManagerUtil, watchServiceExecutor, fileCleanerService, testWatchEventCallBack);
    // then and verify
    diskManager.setupDiskManagerThread();
    diskManager.setupDiskManagerThread();
    Thread.sleep(3000);
    filePath = tempDir.resolve(FILE_NAME);
    Files.write(filePath, Collections.singletonList(MOCK_VALUE));
    // then
    try {
        diskManager.setupDiskManagerThread();
        Thread.sleep(3000);
    } catch (EdgeConnectorForKVSException | InterruptedException e) {
        assertEquals(e.getClass(), EdgeConnectorForKVSException.class);
    }
}
Also used : EdgeConnectorForKVSException(com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException) TestWatchEventCallBack(com.aws.iot.edgeconnectorforkvs.diskmanager.callback.TestWatchEventCallBack) ArrayList(java.util.ArrayList) EdgeConnectorForKVSConfiguration(com.aws.iot.edgeconnectorforkvs.model.EdgeConnectorForKVSConfiguration) WatchEvent(java.nio.file.WatchEvent) Test(org.junit.jupiter.api.Test)

Example 4 with EdgeConnectorForKVSException

use of com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException in project aws-iot-greengrass-edge-connector-for-kinesis-video-stream by awslabs.

the class DiskManagerTest method testWatchService_Path_Register_Failed_Case.

@Test
public void testWatchService_Path_Register_Failed_Case() {
    // when
    List<EdgeConnectorForKVSConfiguration> edgeConnectorForKVSConfigurationList = Collections.singletonList(EdgeConnectorForKVSConfiguration.builder().videoRecordFolderPath(Paths.get("NonExistentFile.txt")).localDataRetentionPeriodInMinutes(LOCAL_DATA_RETENTION_PERIOD_IN_MINUTES).build());
    List<WatchEvent<?>> events = new ArrayList<>();
    testWatchEventCallBack = new TestWatchEventCallBack(events);
    diskManager = new DiskManager(edgeConnectorForKVSConfigurationList, diskManagerUtil, watchServiceExecutor, fileCleanerService, testWatchEventCallBack);
    // then
    try {
        diskManager.setupDiskManagerThread();
    } catch (EdgeConnectorForKVSException e) {
        assertEquals(e.getClass(), EdgeConnectorForKVSException.class);
    }
}
Also used : EdgeConnectorForKVSException(com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException) TestWatchEventCallBack(com.aws.iot.edgeconnectorforkvs.diskmanager.callback.TestWatchEventCallBack) ArrayList(java.util.ArrayList) EdgeConnectorForKVSConfiguration(com.aws.iot.edgeconnectorforkvs.model.EdgeConnectorForKVSConfiguration) WatchEvent(java.nio.file.WatchEvent) Test(org.junit.jupiter.api.Test)

Example 5 with EdgeConnectorForKVSException

use of com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException in project aws-iot-greengrass-edge-connector-for-kinesis-video-stream by awslabs.

the class JobScheduler method stopAllCameras.

/**
 * Stops the Quartz Scheduler for all cameras
 */
public void stopAllCameras() {
    try {
        log.info("Stopping job scheduler!");
        Scheduler sched = this.schedulerFactory.getScheduler();
        log.info("Shutting Down Scheduler");
        sched.shutdown(true);
    } catch (SchedulerException ex) {
        final String errorMessage = String.format("Error stopping scheduler for all cameras: " + ex.getMessage());
        log.error(errorMessage);
        throw new EdgeConnectorForKVSException(errorMessage, ex);
    }
}
Also used : EdgeConnectorForKVSException(com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException) SchedulerException(org.quartz.SchedulerException) Scheduler(org.quartz.Scheduler)

Aggregations

EdgeConnectorForKVSException (com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSException)17 ArrayList (java.util.ArrayList)7 EdgeConnectorForKVSConfiguration (com.aws.iot.edgeconnectorforkvs.model.EdgeConnectorForKVSConfiguration)4 Scheduler (org.quartz.Scheduler)4 SchedulerException (org.quartz.SchedulerException)4 IOException (java.io.IOException)3 DescribeAssetResponse (software.amazon.awssdk.services.iotsitewise.model.DescribeAssetResponse)3 StreamManagerException (com.amazonaws.greengrass.streammanager.client.exception.StreamManagerException)2 TestWatchEventCallBack (com.aws.iot.edgeconnectorforkvs.diskmanager.callback.TestWatchEventCallBack)2 EdgeConnectorForKVSUnrecoverableException (com.aws.iot.edgeconnectorforkvs.model.exceptions.EdgeConnectorForKVSUnrecoverableException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 WatchEvent (java.nio.file.WatchEvent)2 List (java.util.List)2 ExecutionException (java.util.concurrent.ExecutionException)2 Test (org.junit.jupiter.api.Test)2 JobDetail (org.quartz.JobDetail)2 MessageStreamDefinition (com.amazonaws.greengrass.streammanager.model.MessageStreamDefinition)1 ExportDefinition (com.amazonaws.greengrass.streammanager.model.export.ExportDefinition)1 IoTSiteWiseConfig (com.amazonaws.greengrass.streammanager.model.export.IoTSiteWiseConfig)1 AssetPropertyValue (com.amazonaws.greengrass.streammanager.model.sitewise.AssetPropertyValue)1