Search in sources :

Example 1 with DeviceStateObserver

use of com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver in project mbed-cloud-sdk-java by ARMmbed.

the class ConnectExamples method subscribeToDeviceStateChanges.

/**
 * Subscribes to device state changes.
 * <p>
 * Note: This example introduces new high level abstraction objects such as Observer
 */
@Example
public void subscribeToDeviceStateChanges() {
    ConnectionOptions config = Configuration.get();
    Connect api = new Connect(config);
    try {
        // Creating an Observer listening to device state changes for devices whose ids start with 016 and for
        // devices which are newly registered or expired.
        // For more information about backpressure strategies, please have a look at related documentation:
        // https://github.com/ReactiveX/RxJava/wiki/Backpressure
        DeviceStateObserver observer = api.subscribe().deviceState(DeviceStateFilterOptions.newFilter().likeDevice("016%").inDeviceStates(Arrays.asList(DeviceState.REGISTRATION, DeviceState.EXPIRED_REGISTRATION)), BackpressureStrategy.BUFFER);
        // Printing device changes when they happen.
        observer.flow().subscribe(System.out::println);
        // Listening to device state changes for 2 minutes.
        Thread.sleep(120000);
        // Stopping notification pull channel.
        api.stopNotifications();
        Thread.sleep(100);
        api.shutdownConnectService();
    } catch (Exception e) {
        e.printStackTrace();
        logError("last API Metadata", api.getLastApiMetadata());
        try {
            api.stopNotifications();
            Thread.sleep(100);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        api.shutdownConnectService();
        fail(e.getMessage());
    }
}
Also used : DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) Connect(com.arm.mbed.cloud.sdk.Connect) ConnectionOptions(com.arm.mbed.cloud.sdk.common.ConnectionOptions) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) AbstractExample(utils.AbstractExample) Example(utils.Example)

Example 2 with DeviceStateObserver

use of com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver 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 3 with DeviceStateObserver

use of com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver in project mbed-cloud-sdk-java by ARMmbed.

the class TestSubscriptionObserversStore method testDeviceState.

/**
 * Tests subscriptions to device state changes
 */
@Test
public void testDeviceState() {
    Future<?> handle = null;
    ScheduledExecutorService executor = null;
    try {
        List<DeviceStateNotification> receivedNotifications = new LinkedList<>();
        SubscriptionObserversStore store = new SubscriptionObserversStore(Schedulers.computation());
        DeviceStateObserver obs1 = store.deviceState(new DeviceStateFilterOptions().likeDevice("016%33e").equalDeviceState(DeviceState.REGISTRATION_UPDATE), BackpressureStrategy.BUFFER);
        // We are only interested in one value of obs1
        Future<DeviceStateNotification> future = obs1.futureOne();
        DeviceStateObserver obs2 = store.deviceState(DeviceStateFilterOptions.newFilter().likeDevice("016%2b7").equalDeviceState(DeviceState.REGISTRATION_UPDATE), BackpressureStrategy.BUFFER);
        assertTrue(store.hasObservers());
        assertTrue(store.hasObservers(SubscriptionType.DEVICE_STATE_CHANGE));
        assertFalse(store.hasObservers(SubscriptionType.NOTIFICATION));
        assertEquals(2, store.listAll().size());
        assertEquals(2, store.listAll(SubscriptionType.DEVICE_STATE_CHANGE).size());
        assertNull(store.listAll(SubscriptionType.NOTIFICATION));
        // Generating notifications
        @SuppressWarnings("boxing") List<DeviceStateNotification> notifications = Stream.iterate(0, n -> n + 1).limit(102).map(i -> {
            return (i % 2 == 0) ? new DeviceStateNotification((i % 5 == 0) ? DeviceState.REGISTRATION_UPDATE : DeviceState.EXPIRED_REGISTRATION, "0161661e9ce10000000000010010033e") : new DeviceStateNotification((i % 5 == 0) ? DeviceState.REGISTRATION_UPDATE : DeviceState.REGISTRATION, "0161661edbab000000000001001002b7");
        }).collect(Collectors.toList());
        obs2.addCallback(new NotificationCallback<>(new Callback<DeviceStateNotification>() {

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

            private int i = 0;

            @Override
            public void run() {
                if (i < notifications.size()) {
                    try {
                        store.notify(SubscriptionType.DEVICE_STATE_CHANGE, notifications.get(i));
                    } catch (MbedCloudException e) {
                        e.printStackTrace();
                    }
                    i++;
                }
            }
        }, 0, Interval, TimeUnit.MILLISECONDS);
        // Waiting for all notifications to be emitted
        Thread.sleep((notifications.size() + 1) * Interval);
        DeviceStateNotification receivedNotificationForObs1 = future.get(2, TimeUnit.SECONDS);
        assertNotNull(receivedNotificationForObs1);
        assertEquals("0161661e9ce10000000000010010033e", receivedNotificationForObs1.getDeviceId());
        assertEquals(DeviceState.REGISTRATION_UPDATE, receivedNotificationForObs1.getState());
        assertFalse(receivedNotifications.isEmpty());
        // odd Multiples of 5 between 0 and 102: 10
        assertEquals(10, receivedNotifications.size());
        // Observer 2 only cares about changes related to devices like 016%2b7 and REGISTRATION_UPDATE state
        receivedNotifications.forEach(n -> {
            assertEquals("0161661edbab000000000001001002b7", n.getDeviceId());
            assertEquals(DeviceState.REGISTRATION_UPDATE, n.getState());
        });
        assertTrue(store.hasObserver(obs1));
        store.completeAll();
        store.unsubscribeAll();
        assertFalse(store.hasObservers());
        assertFalse(store.hasObserver(obs1));
        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 : DeviceState(com.arm.mbed.cloud.sdk.subscribe.model.DeviceState) SubscriptionType(com.arm.mbed.cloud.sdk.subscribe.SubscriptionType) Future(java.util.concurrent.Future) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Assert.fail(org.junit.Assert.fail) NotificationCallback(com.arm.mbed.cloud.sdk.subscribe.NotificationCallback) Schedulers(io.reactivex.schedulers.Schedulers) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) LinkedList(java.util.LinkedList) DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) BackpressureStrategy(io.reactivex.BackpressureStrategy) Assert.assertNotNull(org.junit.Assert.assertNotNull) 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) Assert.assertNull(org.junit.Assert.assertNull) Stream(java.util.stream.Stream) Assert.assertFalse(org.junit.Assert.assertFalse) DeviceStateNotification(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification) Assert.assertEquals(org.junit.Assert.assertEquals) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) DeviceStateObserver(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver) LinkedList(java.util.LinkedList) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) DeviceStateNotification(com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification) 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) MbedCloudException(com.arm.mbed.cloud.sdk.common.MbedCloudException) Test(org.junit.Test)

Aggregations

DeviceStateObserver (com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateObserver)3 Callback (com.arm.mbed.cloud.sdk.common.Callback)2 MbedCloudException (com.arm.mbed.cloud.sdk.common.MbedCloudException)2 NotificationCallback (com.arm.mbed.cloud.sdk.subscribe.NotificationCallback)2 DeviceState (com.arm.mbed.cloud.sdk.subscribe.model.DeviceState)2 DeviceStateFilterOptions (com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateFilterOptions)2 DeviceStateNotification (com.arm.mbed.cloud.sdk.subscribe.model.DeviceStateNotification)2 BackpressureStrategy (io.reactivex.BackpressureStrategy)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Executors (java.util.concurrent.Executors)2 Future (java.util.concurrent.Future)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 TimeUnit (java.util.concurrent.TimeUnit)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2 Assert.assertEquals (org.junit.Assert.assertEquals)2 Assert.assertFalse (org.junit.Assert.assertFalse)2 Assert.assertTrue (org.junit.Assert.assertTrue)2 Assert.fail (org.junit.Assert.fail)2