Search in sources :

Example 6 with Resource

use of com.arm.mbed.cloud.sdk.connect.model.Resource in project mbed-cloud-sdk-java by ARMmbed.

the class TestNotificationHandling method testNotifyNotificationMessage.

@SuppressWarnings("boxing")
@Test
public void testNotifyNotificationMessage() {
    Future<?> handle = null;
    ScheduledExecutorService executor = null;
    String[] payloads = { "MQ==", "Mg==", "Mw==", "NA==", "NQ==" };
    try {
        executor = Executors.newScheduledThreadPool(1);
        NotificationHandlersStore store = new NotificationHandlersStore(null, null, executor, null);
        List<Integer> receivedNotificationsUsingObservers = new LinkedList<>();
        List<Integer> receivedNotificationsUsingCallbacks = new LinkedList<>();
        List<Throwable> receivedErrorsUsingCallbacks = new LinkedList<>();
        String deviceId = "015f4ac587f500000000000100100249";
        String resourcePath = "/3200/0/5501";
        Resource resource = new Resource(deviceId, resourcePath);
        store.createResourceSubscriptionObserver(resource, BackpressureStrategy.BUFFER).subscribe(object -> receivedNotificationsUsingObservers.add(Integer.parseInt(String.valueOf(object.getRawValue()))));
        store.registerSubscriptionCallback(resource, new Callback<Object>() {

            @Override
            public void execute(Object arg) {
                System.out.println("Received notification: " + arg);
                receivedNotificationsUsingCallbacks.add(Integer.parseInt(String.valueOf(arg)));
            }
        }, new Callback<Throwable>() {

            @Override
            public void execute(Throwable arg) {
                System.err.println("Error happened during notification handling: " + arg);
                receivedErrorsUsingCallbacks.add(arg);
            }
        });
        // The following should not have any impact.
        store.deregisterNotificationSubscriptionCallback(new Resource(deviceId, "/3200/0/5502"));
        store.removeResourceSubscriptionObserver(new Resource(deviceId, "/3200/0/5503"));
        int Interval = 100;
        handle = executor.scheduleWithFixedDelay(new Runnable() {

            List<String> payloadList = Arrays.asList(payloads);

            private int i = 0;

            @Override
            public void run() {
                if (i < payloadList.size()) {
                    NotificationMessage notifications = new NotificationMessage();
                    NotificationData notification = new NotificationData();
                    notification.setEp(deviceId);
                    notification.setPath(resourcePath);
                    notification.setPayload(payloadList.get(i));
                    notifications.addNotificationsItem(notification);
                    store.notify(null);
                    store.notify(notifications);
                    i++;
                }
            }
        }, 0, Interval, TimeUnit.MILLISECONDS);
        Thread.sleep((payloads.length + 1) * Interval);
        assertTrue(receivedErrorsUsingCallbacks.isEmpty());
        assertFalse(receivedNotificationsUsingCallbacks.isEmpty());
        assertFalse(receivedNotificationsUsingObservers.isEmpty());
        for (int i = 0; i < payloads.length; i++) {
            assertEquals(i + 1, receivedNotificationsUsingCallbacks.get(i), 0);
            assertEquals(i + 1, receivedNotificationsUsingObservers.get(i), 0);
        }
        store.shutdown();
        if (handle != null) {
            handle.cancel(true);
        }
        executor.shutdownNow();
    } catch (Exception e) {
        if (handle != null) {
            handle.cancel(true);
        }
        if (executor != null) {
            executor.shutdownNow();
        }
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Resource(com.arm.mbed.cloud.sdk.connect.model.Resource) LinkedList(java.util.LinkedList) NotificationMessage(com.arm.mbed.cloud.sdk.internal.mds.model.NotificationMessage) LinkedList(java.util.LinkedList) List(java.util.List) NotificationData(com.arm.mbed.cloud.sdk.internal.mds.model.NotificationData) Test(org.junit.Test)

Example 7 with Resource

use of com.arm.mbed.cloud.sdk.connect.model.Resource in project mbed-cloud-sdk-java by ARMmbed.

the class TestNotificationHandling method testDeviceState.

/**
 * Tests subscriptions to device state changes
 */
@Test
public void testDeviceState() {
    Future<?> handle = null;
    ScheduledExecutorService executor = null;
    try {
        List<DeviceStateNotification> receivedNotifications = new LinkedList<>();
        executor = Executors.newScheduledThreadPool(1);
        NotificationHandlersStore store = new NotificationHandlersStore(null, null, executor, null);
        DeviceStateObserver obs1 = store.getSubscriptionManager().deviceState(new DeviceStateFilterOptions().likeDevice("016%33e").equalDeviceState(DeviceState.REGISTRATION_UPDATE), BackpressureStrategy.BUFFER);
        // Generating notifications
        @SuppressWarnings("boxing") List<NotificationMessage> notifications = Stream.iterate(0, n -> n + 1).limit(32).map(i -> {
            NotificationMessage message = new NotificationMessage();
            EndpointData data = new EndpointData();
            if (i % 5 == 0) {
                data.setEp("0161661e9ce10000000000010010033e");
            } else {
                data.setEp("0161661edbab000000000001001002b7");
            }
            data.setEpt("random");
            data.setQ(false);
            data.setResources(Stream.iterate(0, n -> n + 1).limit(50).map(v -> {
                final ResourcesData resource = new ResourcesData();
                resource.setPath("/" + v);
                resource.setObs(true);
                return resource;
            }).collect(Collectors.toList()));
            if (i % 2 == 0) {
                message.addRegUpdatesItem(data);
            } else {
                message.addRegistrationsItem(data);
            }
            return message;
        }).collect(Collectors.toList());
        obs1.addCallback(new NotificationCallback<>(new Callback<DeviceStateNotification>() {

            @Override
            public void execute(DeviceStateNotification arg) {
                receivedNotifications.add(arg);
            }
        }, null));
        int Interval = 300;
        handle = executor.scheduleWithFixedDelay(new Runnable() {

            private int i = 0;

            @Override
            public void run() {
                if (i < notifications.size()) {
                    store.notify(notifications.get(i));
                    i++;
                }
            }
        }, 0, Interval, TimeUnit.MILLISECONDS);
        // Waiting for all notifications to be emitted
        Thread.sleep((notifications.size() + 1) * Interval);
        assertFalse(receivedNotifications.isEmpty());
        // Only multiples of 10 between 0 and 32
        assertEquals(4, receivedNotifications.size());
        // Observer only cares about changes related to devices like 016%33e and REGISTRATION_UPDATE state
        receivedNotifications.forEach(n -> {
            assertEquals("0161661e9ce10000000000010010033e", n.getDeviceId());
            assertEquals(DeviceState.REGISTRATION_UPDATE, n.getState());
        });
        if (handle != null) {
            handle.cancel(true);
        }
        executor.shutdownNow();
    } catch (Exception e) {
        if (handle != null) {
            handle.cancel(true);
        }
        if (executor != null) {
            executor.shutdownNow();
        }
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Arrays(java.util.Arrays) DeviceState(com.arm.mbed.cloud.sdk.subscribe.model.DeviceState) NotificationData(com.arm.mbed.cloud.sdk.internal.mds.model.NotificationData) Resource(com.arm.mbed.cloud.sdk.connect.model.Resource) Future(java.util.concurrent.Future) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ResourcesData(com.arm.mbed.cloud.sdk.internal.mds.model.ResourcesData) Assert.fail(org.junit.Assert.fail) NotificationCallback(com.arm.mbed.cloud.sdk.subscribe.NotificationCallback) LinkedList(java.util.LinkedList) EndpointData(com.arm.mbed.cloud.sdk.internal.mds.model.EndpointData) DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) BackpressureStrategy(io.reactivex.BackpressureStrategy) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Callback(com.arm.mbed.cloud.sdk.common.Callback) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) DeviceStateFilterOptions(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateFilterOptions) List(java.util.List) Stream(java.util.stream.Stream) Assert.assertFalse(org.junit.Assert.assertFalse) DeviceStateNotification(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification) NotificationMessage(com.arm.mbed.cloud.sdk.internal.mds.model.NotificationMessage) Assert.assertEquals(org.junit.Assert.assertEquals) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) ResourcesData(com.arm.mbed.cloud.sdk.internal.mds.model.ResourcesData) LinkedList(java.util.LinkedList) DeviceStateNotification(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification) EndpointData(com.arm.mbed.cloud.sdk.internal.mds.model.EndpointData) DeviceStateFilterOptions(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateFilterOptions) NotificationCallback(com.arm.mbed.cloud.sdk.subscribe.NotificationCallback) Callback(com.arm.mbed.cloud.sdk.common.Callback) NotificationMessage(com.arm.mbed.cloud.sdk.internal.mds.model.NotificationMessage) Test(org.junit.Test)

Example 8 with Resource

use of com.arm.mbed.cloud.sdk.connect.model.Resource in project mbed-cloud-sdk-java by ARMmbed.

the class Connect method getResource.

/**
 * Gets device's resource.
 * <p>
 * Example:
 *
 * <pre>
 * {@code
 * try {
 *     Device device = new Device();
 *     device.setId("015f4ac587f500000000000100100249");
 *
 *     String resourcePath = "/3201/0/5853";
 *
 *     Resource resource = connectApi.getResource(device, resourcePath);
 *     System.out.println("Confirmed resource path: " + resource.getPath());
 *     assert resourcePath == resource.getPath();
 * } catch (MbedCloudException e) {
 *     e.printStackTrace();
 * }
 * }
 * </pre>
 *
 * @param device
 *            Device.
 * @param resourcePath
 *            Path of the resource to get
 * @return resource present on the device.
 * @throws MbedCloudException
 *             if a problem occurred during request processing.
 */
@API
@Nullable
public Resource getResource(@NonNull Device device, @NonNull String resourcePath) throws MbedCloudException {
    checkNotNull(device, TAG_DEVICE);
    checkNotNull(device.getId(), TAG_DEVICE_ID);
    checkNotNull(resourcePath, TAG_RESOURCE_PATH);
    final List<Resource> resources = listResources(device);
    if (resources == null || resources.isEmpty()) {
        return null;
    }
    for (final Resource resource : resources) {
        if (ApiUtils.comparePaths(resourcePath, resource.getPath())) {
            return resource;
        }
    }
    return null;
}
Also used : Resource(com.arm.mbed.cloud.sdk.connect.model.Resource) API(com.arm.mbed.cloud.sdk.annotations.API) Nullable(com.arm.mbed.cloud.sdk.annotations.Nullable)

Example 9 with Resource

use of com.arm.mbed.cloud.sdk.connect.model.Resource in project mbed-cloud-sdk-java by ARMmbed.

the class Connect method listObservableResources.

/**
 * Lists device's observable resources.
 *
 * @see Resource#isObservable()
 *      <p>
 *      Example:
 *
 *      <pre>
 * {@code
 * try {
 *     Device device = new Device();
 *     device.setId("015f4ac587f500000000000100100249");
 *
 *     List<Resource> resources = connectApi.listObservableResources(device);
 *     for (Resource resource : resources) {
 *         System.out.println("Resource path: " + resource.getPath());
 *     }
 * } catch (MbedCloudException e) {
 *     e.printStackTrace();
 * }
 * }
 *      </pre>
 *
 * @param device
 *            Device.
 * @return list of observable resources present on a device.
 * @throws MbedCloudException
 *             if a problem occurred during request processing.
 */
@API
@Nullable
public List<Resource> listObservableResources(@NonNull Device device) throws MbedCloudException {
    final List<Resource> resources = listResources(device);
    if (resources == null || resources.isEmpty()) {
        return null;
    }
    final List<Resource> observableResources = new LinkedList<>();
    for (final Resource resource : resources) {
        if (resource.isObservable()) {
            observableResources.add(resource);
        }
    }
    return observableResources.isEmpty() ? null : observableResources;
}
Also used : Resource(com.arm.mbed.cloud.sdk.connect.model.Resource) LinkedList(java.util.LinkedList) API(com.arm.mbed.cloud.sdk.annotations.API) Nullable(com.arm.mbed.cloud.sdk.annotations.Nullable)

Example 10 with Resource

use of com.arm.mbed.cloud.sdk.connect.model.Resource in project mbed-cloud-sdk-java by ARMmbed.

the class Connect method addResourceSubscription.

/**
 * Subscribes to a resource.
 * <p>
 * Example:
 *
 * <pre>
 * {@code
 * try {
 *     String deviceId = "015f4ac587f500000000000100100249";
 *     String resourcePath = "/3200/0/5501";
 *     Resource buttonResource = new Resource(deviceId, resourcePath);
 *
 *     connectApi.addResourceSubscription(buttonResource);
 * } catch (MbedCloudException e) {
 *     e.printStackTrace();
 * }
 * }
 * </pre>
 *
 * @param resource
 *            resource to subscribe to.
 * @throws MbedCloudException
 *             if a problem occurred during request processing.
 */
@API
public void addResourceSubscription(@NonNull Resource resource) throws MbedCloudException {
    checkNotNull(resource, TAG_RESOURCE);
    checkModelValidity(resource, TAG_RESOURCE);
    final Resource finalResource = resource;
    CloudCaller.call(this, "addResourceSubscription()", null, new CloudCall<Void>() {

        @Override
        public Call<Void> call() {
            return endpoint.getSubscriptions().v2SubscriptionsDeviceIdResourcePathPut(finalResource.getDeviceId(), ApiUtils.normalisePath(finalResource.getPath()));
        }
    });
}
Also used : Call(retrofit2.Call) CloudCall(com.arm.mbed.cloud.sdk.common.CloudCaller.CloudCall) Resource(com.arm.mbed.cloud.sdk.connect.model.Resource) API(com.arm.mbed.cloud.sdk.annotations.API)

Aggregations

Resource (com.arm.mbed.cloud.sdk.connect.model.Resource)15 MbedCloudException (com.arm.mbed.cloud.sdk.common.MbedCloudException)9 Connect (com.arm.mbed.cloud.sdk.Connect)8 ConnectionOptions (com.arm.mbed.cloud.sdk.common.ConnectionOptions)8 AbstractExample (utils.AbstractExample)8 Example (utils.Example)8 Device (com.arm.mbed.cloud.sdk.devicedirectory.model.Device)7 DeviceListOptions (com.arm.mbed.cloud.sdk.devicedirectory.model.DeviceListOptions)6 API (com.arm.mbed.cloud.sdk.annotations.API)5 LinkedList (java.util.LinkedList)4 CloudCall (com.arm.mbed.cloud.sdk.common.CloudCaller.CloudCall)3 NotificationData (com.arm.mbed.cloud.sdk.internal.mds.model.NotificationData)3 NotificationMessage (com.arm.mbed.cloud.sdk.internal.mds.model.NotificationMessage)3 Call (retrofit2.Call)3 Nullable (com.arm.mbed.cloud.sdk.annotations.Nullable)2 Callback (com.arm.mbed.cloud.sdk.common.Callback)2 TimePeriod (com.arm.mbed.cloud.sdk.common.TimePeriod)2 List (java.util.List)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 Test (org.junit.Test)2