User Tools

Site Tools


notification_service_-_programming_guide

IoTivity Notification Service - Programming Guide


This page will guide you how to install and run IoTivity notification services. The sample provider and consumer application will let you test the notification service and build up the services.

Build Notification Service


Notification service project is located under {IoTivity root}/service/notification folder. The project consists of provider and consumer services which are based on C language and Iotivity csdk stack. In addition, wrapper fuctionalitiy is provided to develop the notification service using C++ and Java language.

Build Notification Service

Build : ~iotivity $ scons service/notification TARGET_TRANSPORT=IP
Unittest : ~iotivity $ scons service/notification TEST=1

Run Provider Sample

~iotivity/out/linux/x86/release/service/notification/examples/linux $ ./notificationprovider

Run Consumer Sample

~iotivity/out/linux/x86/release/service/notification/examples/linux $ ./notificationconsumer

API Usages


This section is going to describe how to use Notification Service APIs based on C language. The sample code using notification service APIs helps that you make a notification application for each service. Refer to the sample code as follows. Please refer to API documentation for more : https://api-docs.iotivity.org/latest-c/

To start notification service, it is required to initiate IoTivity stack in advance. After OCInit, the application starts notification service as follows.

// [Provider]
NSProviderConfig config;
config.subcontrollability = true;
config.subRequestCallback = subscribeRequestCallback;
config.syncInfoCallback = syncCallback;
config.userInfo = OICStrdup("OCF_NOTIFICATION");
NSStartProvider(config);
// [Consumer]
NSConsumerConfig cfg;
cfg.changedCb = onProviderChanged;
cfg.messageCb = onNotificationPosted;
cfg.syncInfoCb = onNotificationSync;
NSStartConsumer(cfg);

To discover provider and consumer services (D2D Only), each service works automatically once it starts the service. Provider service creates notification resources and sends presence to consumers. On the other hand, consumer service monitors the presence and finds the notification resources. Additionally, you can call NSRescanProvider API to discover providers as the explicit way.

// Request discovery manually
NSResult NSRescanProvider();

To subscribe notification service, provider and consumer applications are required to conduct tasks for subscription as policy. When you set subControllability flag as true, you might receive subscription request from consumer service on callback function which is set by NSProviderConfig as above, and then you have to send an acceptance(allow or deny) in reply using NSAcceptSubscription API.

// [When the provider set subControllability flag as true]
void subscribeRequestCallback(NSConsumer *consumer)
{
    printf("consumer requested to subscribe");
    printf("NS_APP Consumer Device ID: %s\n", consumer->consumerId);

    NSAcceptSubscription(consumer->consumerId, true);
}

Other case, when you set subControllability flag as false, consumer application should request to subscribe to the provider which is discovered by consumer service.

// [When the provider set subControllability flag as false, consumer service invokes callback]
void onProviderChanged(NSProvider * provider, NsProviderState response)
{
    if(response == NS_DISCOVERED)
    {
      printf("notification resource discovered\n");
      printf("subscribe result %d\n", NSSubscribe(provider->providerId));
    }
}

To notify message, provider application uses NSSendMessage API. The API has a parameter as NSMessage created by NSCreateMessage API which generates an unique message ID. Note that an invalid message ID is not allowed for notification service to work properly.

// provider send message to subscribed consumers.
NSMessage * msg = NSCreateMessage();

msg->title = OICStrdup(title);
msg->contentText = OICStrdup(body);
msg->sourceName = OICStrdup("OCF");

if(topic[0] != '\0')
{
    msg->topic = OICStrdup(topic);
}

NSSendMessage(msg);

When a provider notifies a message, subscribing consumer might receive the message on callback function.

// consumer receives message on callback.
void onNotificationPosted(NSMessage * notification)
{
    printf("id : %lld\n", (long long int)notification->messageId);
    printf("title : %s\n", notification->title);
    printf("content : %s\n", notification->contentText);
    printf("source : %s\n", notification->sourceName);
    if (notification->topic && strlen(notification->topic) > 0)
    {
        printf("topic : %s\n", notification->topic);
    }
}

To synchronize the notification state, a provider or consumer sends the state of notification message which has two types of the state, read and deleted. The provider application uses NSProviderSendSyncInfo API with the state changed by its own device.

// To synchronize the notification state on provider service
/**
 * Send read-check to provider in order to synchronize notification status with other consumers
 * @param[in]  message  Notification message to synchronize the status
 * @return ::NS_OK or result code of NSResult
 */
NSResult NSProviderSendSyncInfo(uint64_t messageId, NSSyncType type);

Others, consumer application requests to send the state using NSConsumerSendSyncInfo API. When consumer service sends the state of the notification message, provider service retransmit it to other subscribing consumers.

// To synchronize the notification state on consumer service
/**
 * Send sync type to provider in order to synchronize notification status with other consumers
 * when consumer consumes the notification such as READ, DELETE
 * @param[in]  providerId  Provider id of the Notification message
 * @param[in]  messageId  Notification message id to synchronize the status
 * @param[in]  type  changed notification status from NSSyncType
 * @return ::NS_OK or result code of NSResult
 */
NSResult NSConsumerSendSyncInfo(
        const char * providerId, uint64_t messageId, NSSyncType type);

To subscribe interest topics, first step is topic registration from provider application. Here the APIs, NSProviderRegisterTopic and NSProviderUnregisterTopic, are used to register and deregister, respectively.

// Add and delete provider’s topic list
case 5:
    printf("NSProviderAddTopic\n");
    NSProviderRegisterTopic("OCF_TOPIC1");
    NSProviderRegisterTopic("OCF_TOPIC2");
    NSProviderRegisterTopic("OCF_TOPIC3");
    NSProviderRegisterTopic("OCF_TOPIC4");
    break;

case 6:
    printf("NSProviderDeleteTopic\n");
    NSProviderUnregisterTopic("OCF_TOPIC2");
    break;

After provider application has registered the topics, consumer application requests to get the list of topics to provider so that the consumer application subscribes interest topics.

// Get all of the topics which have been registered by provider applicaion.
case 3:
    printf("3. Get Topics\n");
    if(g_provider)
    {
        g_topicLL = NSConsumerGetTopicList(g_provider->providerId);
    }
    break;
    
// Subscribe interest topics on consumer application.
case 4:
    printf("4. Select Topics\n");

    if (g_provider && g_topicLL)
    {
        NSTopicLL * iter = g_topicLL;
        int i = 0;
        while (iter)
        {
            iter->state = (i++)%2;
            printf("Topic Name: %s\t Topic State: %d\n",
                iter->topicName, iter->state);
            iter = iter->next;
        }
        NSConsumerUpdateTopicList(g_provider->providerId, g_topicLL);
    }
    break;

To enable Remote Service, the step of cloud login is required. Please read cloud programming guide page to login cloud server(RD). After haviing performed cloud login, call NSProviderEnagleRemoteService with the remote server address. For example, the address format is coap+tcp with ip “10.20.30.40” and port number of “1234”. Then the provider service publishes the notification resource to cloud interface in order to run as remote notificaion service. To terminate the remote service, provider applicaion is needed to call NSProviderDisableRemoteService API after logout from cloud server.

// remote service on provider
case 21:
    printf("CLOUD_ADDRESS");
    if(!IsCloudLoggedin())
    {
        printf("Login required");
        break;
    }
    NSProviderEnableRemoteService(CLOUD_ADDRESS);                
    break;
case 22:
    printf("Disable Remote Service");
    if(!IsCloudLoggedin())
    {
        printf("Login required");
        break;
    }
    NSProviderDisableRemoteService(CLOUD_ADDRESS);
    break;

For consumer, discovery and subscription works as the same in device to device afer calling NSConsumerEnableRemoteService API with the address of the remote server logged in.

// remote service on consumer
case 21:
    printf("Enable Remote Service");
    if(!IsCloudLoggedin())
    {
        printf("Cloud Login required");
        break;
    }
    NSConsumerEnableRemoteService(CLOUD_ADDRESS);
    break;

To terminate notification service, notification service offers the API of stop service. When call the stop API, both of notification services will deallocate whole used memory and information of other services.

// stop provider service.
case 0:
    NSStopProvider();
    isExit = true;
    break;
// stop consumer service.
case 2:
    printf("2. Stop Consumer");
    NSStopConsumer();
    break;

Build Notification Service For Android

Build iotivity code with command to build for Android

Build : ~iotivity $ scons TARGET_OS=android TARGET_ARCH=armeabi TARGET_TRANSPORT=IP RELEASE=1

Sample Android application for Provider and Consumer are available respectively at below paths.

~iotivity/service/notification/examples/android/NotiConsumerExample/app/build/outputs/apk $ adb install app-debug.apk
~iotivity/service/notification/examples/android/NotiProviderExample/app/build/outputs/apk $ adb install app-debug.apk

Installation

1. Install “NotiProviderExample” and “NotiConsumerExample” applications in different android mobile.

2. connect both mobile to same wifi network.

Testing Steps

Scenario-1 “Acceptor as provider”

1. [NotiProviderExample] Open app and select/unselect checkbox to allow/deny application to read your notification, then click back button to go to Main UI.

2. [NotiProviderExample] Select radiobutton for choosing acceptor as provider.

3. [NotiProviderExample] Click on Start button to start Notification Provider Service.

4. [NotiConsumerExample] Open app and Click on Start button to start Notification Consumer Service. 

    -> [NotiProviderExample] Log of "onConsumerSubscribed" callback with consumer object contating consumerId is Printed

    -> [NotiConsumerExample] Log of "onProviderDiscovered" callback with provider object contating providerId is Printed

    -> [NotiConsumerExample] Log of "onProviderStateReceived" callback with provider State as 'ALLOW' is Printed

5. [NotiProviderExample] Click "Register Topic" button.

    -> [NotiConsumerExample] Log of "onProviderStateReceived" callback with provider State as 'TOPIC' is Printed

6. [NotiProviderExample] Click "Set Topic" button.

    -> [NotiConsumerExample] Log of "onProviderStateReceived" callback with provider State as 'TOPIC' is Printed

7. [NotiProviderExample] Add Title, Body and Topic and Click "Send Notification" button.
Note: For Testing, Add Topic name as either one of OCF_TOPIC1, OCF_TOPIC2, OCF_TOPIC3, OCF_TOPIC4 or can leave blank 

    -> [NotiConsumerExample] Should get "onMessageReceived" callback with Message object containing the Notification Message

    -> [NotiProviderExample] Should get "onMessageSynchronized" callback with SyncInfo object contating the messageId

8. [NotiProviderExample] Click on Stop button.

    -> [NotiConsumerExample] Should get "onProviderStateReceived" callback with provider State as 'STOPPED'

Scenario-2 “Acceptor as consumer”

1. [NotiProviderExample] Open app and select/unselect checkbox to allow/deny application to read your notification, then click back button to go to Main UI. 

2. [NotiProviderExample] Select radiobutton for choosing acceptor as consumer.
 
3. [NotiProviderExample] Click on Start button to start Notification Provider Service.

4. [NotiConsumerExample] Open app and Click on Start button to start Notification Consumer Service.

    -> [NotiConsumerExample] Log of "onProviderDiscovered" callback with provider object contating providerId is Printed

    -> [NotiConsumerExample] Log of "onProviderStateReceived" callback with provider State as 'ALLOW' is Printed

5. [NotiProviderExample] Click "Register Topic" button.

    -> [NotiConsumerExample] Log of "onProviderStateReceived" callback with provider State as 'TOPIC' is Printed

6. [NotiConsumerExample] Click "Update Topic List" button. 

7. [NotiProviderExample] Add Title, Body and Topic and Click "Send Notification" button.
Note: For Testing, Add Topic name as either one of OCF_TOPIC1, OCF_TOPIC2, OCF_TOPIC3, OCF_TOPIC4 or can leave blank 

    -> [NotiConsumerExample] Should get "onMessageReceived" callback with Message object containing the Notification Message

    -> [NotiProviderExample] Should get "onMessageSynchronized" callback with SyncInfo object contating the messageId

8. [NotiProviderExample] Click on Stop button.

    -> [NotiConsumerExample] Should get "onProviderStateReceived" callback with provider State as 'STOPPED'
notification_service_-_programming_guide.txt · Last modified: 2017/04/06 14:17 by Koenraad Verheyden