This patch is initial version of notification service in IoTivity.
in this patch, included functionality of notification resource creation,
discover, send notification, read and dismiss messages.
Change-Id: I43ff9316d1eff15aabcc817e048f09c811b9a248
Signed-off-by: jyong2.kim <jyong2.kim@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/8077
Reviewed-by: Uze Choi <uzchoi@samsung.com>
Tested-by: Uze Choi <uzchoi@samsung.com>
if target_os in ['linux']:
SConscript('scene-manager/SConscript')
+ #if target_os in ['linux']:
+ #SConscript('notification/SConscript')
+
# Build simulator module
if target_os in ['linux'] and env.get('SIMULATOR', False):
SConscript('simulator/SConscript')
--- /dev/null
+#******************************************************************
+#
+# Copyright 2016 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Notification Service build script
+##
+
+import platform
+Import('env')
+
+if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+ env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+ env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+notification_env = lib_env.Clone()
+
+target_os = env.get('TARGET_OS')
+######################################################################
+# Build flags
+######################################################################
+notification_env.AppendUnique(CPPPATH = ['include'])
+notification_env.AppendUnique(CPPPATH = ['src/common'])
+notification_env.AppendUnique(CPPPATH = ['src/provider'])
+notification_env.AppendUnique(CPPPATH = ['../../resource/csdk/stack/include'])
+notification_env.AppendUnique(CPPPATH = ['../../resource/csdk/connectivity/api'])
+
+notification_env.PrependUnique(LIBS = [
+ 'octbstack',
+ 'oc_logger',
+ 'connectivity_abstraction',
+ 'libcoap'
+ ])
+
+if target_os not in ['windows', 'winrt']:
+ notification_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+ notification_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+
+if target_os == 'linux':
+ notification_env.AppendUnique(LIBS = ['pthread'])
+
+if target_os == 'android':
+ notification_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ notification_env.AppendUnique(LIBS = ['gnustl_shared','log'])
+ notification_env.AppendUnique(LINKFLAGS = ['-Wl,-soname,libnotification_provider.so'])
+
+
+ if not env.get('RELEASE'):
+ notification_env.AppendUnique(LIBS = ['log'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+notification_provider_src = [
+ env.Glob('src/provider/*.c'),
+ env.Glob('src/common/*.c')]
+notification_consumer_src = [
+ #env.Glob('src/common/*.c'),
+ env.Glob('src/consumer/*.c')]
+
+providersdk = notification_env.SharedLibrary('notification_provider', notification_provider_src)
+notification_env.InstallTarget(providersdk, 'libnotification_provider')
+notification_env.UserInstallTargetLib(providersdk, 'libnotification_provider')
+
+consumersdk = notification_env.SharedLibrary('notification_consumer', notification_consumer_src)
+notification_env.InstallTarget(consumersdk, 'libnotification_consumer')
+notification_env.UserInstallTargetLib(consumersdk, 'libnotification_consumer')
+
+providersdk = notification_env.StaticLibrary('notification_provider', notification_provider_src)
+notification_env.InstallTarget(providersdk, 'libnotification_provider')
+notification_env.UserInstallTargetLib(providersdk, 'libnotification_provider')
+
+consumersdk = notification_env.StaticLibrary('notification_consumer', notification_consumer_src)
+notification_env.InstallTarget(consumersdk, 'libnotification_consumer')
+notification_env.UserInstallTargetLib(consumersdk, 'libnotification_consumer')
+
+#notification_env.UserInstallTargetHeader('include/NSProviderIngerface.h',\
+# 'service/notification', 'NSProviderIngerface.h')
+#notification_env.UserInstallTargetHeader('include/NSConsumerIngerface.h',\
+# 'service/notification', 'NSConsumerIngerface.h')
+
+# Go to build Unit test
+#if target_os == 'linux':
+# SConscript('unittest/SConscript')
+
+# Go to build sample apps
+SConscript('examples/SConscript')
+
+# Go to build jni
+if target_os == 'android':
+ SConscript('android/SConscript')
+++ /dev/null
-Initial commit for C++ notification
--- /dev/null
+##
+# Examples build script
+##
+Import('env')
+
+target_os = env.get('TARGET_OS')
+if target_os == 'linux':
+ SConscript('linux/SConscript')
+elif target_os == 'android':
+ SConscript('android/SConscript')
\ No newline at end of file
+++ /dev/null
-Initial commit for folder structure
--- /dev/null
+##
+# Notification build script
+##
+
+Import('env')
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+notification_sample_env = lib_env.Clone()
+
+target_os = env.get('TARGET_OS')
+######################################################################
+# Build flags
+######################################################################
+notification_sample_env.AppendUnique(CPPPATH = ['../../include'])
+notification_sample_env.AppendUnique(CPPPATH = ['../../src/common'])
+notification_sample_env.AppendUnique(CPPPATH = ['../../src/provider'])
+notification_sample_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/stack/include'])
+notification_sample_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/connectivity/api'])
+
+notification_sample_env.PrependUnique(LIBS = [
+ 'octbstack',
+ 'oc_logger',
+ 'connectivity_abstraction',
+ 'libcoap'
+ ])
+
+
+
+if target_os not in ['windows', 'winrt']:
+ notification_sample_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+
+if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
+ notification_sample_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+
+if target_os == 'linux':
+ notification_sample_env.AppendUnique(LIBS = ['pthread'])
+
+if target_os == 'android':
+ notification_sample_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ notification_sample_env.AppendUnique(LIBS = ['gnustl_shared','log'])
+
+ if not env.get('RELEASE'):
+ notification_sample_env.AppendUnique(LIBS = ['log'])
+####################################################################
+# Source files and Targets
+######################################################################
+notification_sample_provider_env = notification_sample_env.Clone()
+
+notification_sample_provider_env.AppendUnique(LIBS = 'libnotification_provider')
+notificationprovider = notification_sample_provider_env.Program('notificationprovider', 'notificationprovider.c')
+i_notificationprovider = notification_sample_provider_env.Install(env.get('BUILD_DIR'), notificationprovider)
+
+notification_sample_consumer_env = notification_sample_env.Clone()
+notification_sample_consumer_env.AppendUnique(LIBS = 'libnotification_consumer')
+notificationconsumer = notification_sample_consumer_env.Program('notificationconsumer', 'notificationconsumer.c')
+i_notificationprovider = notification_sample_consumer_env.Install(env.get('BUILD_DIR'), notificationconsumer)
--- /dev/null
+#include <stdio.h>
+
+#include <unistd.h>
+#include "NSCommon.h"
+#include "NSConsumerInterface.h"
+#include "ocstack.h"
+
+void onNotificationPosted(NSProvider * provider, NSMessage * notification)
+{
+ printf("Notification from : %s:%d\n", ((OCDevAddr *)provider->mUserData)->addr,
+ ((OCDevAddr *)provider->mUserData)->port);
+ printf("id : %s\n", notification->mId);
+ printf("title : %s\n", notification->mTitle);
+ printf("content : %s\n", notification->mContentText);
+// NSDropNSObject(notification);
+ NSRead(notification);
+}
+
+void onDiscoverNotification(NSProvider * provider)
+{
+ printf("notification resource discovered\n");
+ printf("subscribe result %d\n", NSSubscribeProvider(provider));
+ printf("startSubscribing\n");
+}
+
+void onNotificationSync(NSProvider * provider, NSSync * sync)
+{
+ printf("Sync from : %s:%d\n", ((OCDevAddr *)provider->mUserData)->addr,
+ ((OCDevAddr *)provider->mUserData)->port);
+ printf("Sync ID : %s\n", sync->mMessageId);
+ printf("Sync STATE : %d\n", sync->mState);
+}
+
+int main(void)
+{
+
+ printf("start Iotivity\n");
+ if (OCInit1(OC_CLIENT, OC_DEFAULT_FLAGS, OC_DEFAULT_FLAGS) != OC_STACK_OK)
+ {
+ printf("OCInit fail\n");
+ return 0;
+ }
+
+
+
+ printf("start notification consumer service\n");
+ NSResult ret = NSStartConsumer(
+ onDiscoverNotification,
+ onNotificationPosted,
+ onNotificationSync);
+ if(ret != NS_OK)
+ {
+ printf("error discoverNoti %d\n", ret);
+ }
+
+ while (true)
+ {
+ usleep(2000);
+ if(OCProcess() != OC_STACK_OK)
+ {
+ OCStop();
+ break;
+ }
+ }
+
+ return 0;
+}
--- /dev/null
+#include <stdio.h>\r
+#include <stdbool.h>\r
+#include <stdlib.h>\r
+#include "NSCommon.h"\r
+#include "NSProviderInterface.h"\r
+#include "logger.h"\r
+#include "octypes.h"\r
+#include "pthread.h"\r
+\r
+\r
+#define TAG "notiProviderExample"\r
+\r
+extern char *strdup(const char *s);\r
+\r
+bool isExit = false;\r
+\r
+pthread_t processThread;\r
+\r
+int id;\r
+\r
+void OCProcessThread(void * ptr)\r
+{\r
+ (void*) ptr;\r
+ while (!isExit)\r
+ {\r
+ if (OCProcess() != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(ERROR, TAG, "OCStack process error");\r
+ return;\r
+ }\r
+ }\r
+}\r
+\r
+void subscribeRequestCallback(NSConsumer *consumer)\r
+{\r
+ OIC_LOG(INFO, TAG, "consumer requested to subscribe");\r
+ char *cid = consumer->mId;\r
+\r
+ printf("Consumer ID: %s\n", cid);\r
+\r
+ NSAccept(consumer, true);\r
+}\r
+\r
+void syncCallback(NSProvider *provider, NSSync *sync)\r
+{\r
+ OIC_LOG(INFO, TAG, "sync requested");\r
+\r
+ printf("Sync State: %d\n", sync->mState);\r
+\r
+}\r
+\r
+int main()\r
+{\r
+ int num;\r
+\r
+ OIC_LOG(INFO, TAG, "NSStartProvider()");\r
+\r
+ if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(INFO, TAG, "OCStack init error");\r
+ return 0;\r
+ }\r
+\r
+ pthread_create(&processThread, NULL, OCProcessThread, NULL);\r
+\r
+ NSMessage * message = (NSMessage*) OICMalloc(sizeof(NSMessage));\r
+ if (!message)\r
+ {\r
+ OIC_LOG(ERROR, TAG, PCF("Fail to allocate memory"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ while (true)\r
+ {\r
+ char dummy;\r
+\r
+ printf("1. NSStartProvider(Accepter: Provider) \n");\r
+ printf("2. NSStartProvider(Accepter: Consumer) \n");\r
+ printf("3. NSSendNotification() \n");\r
+ printf("4. NSRead \n");\r
+ //printf("5. NSAccept \n");\r
+ printf("6. NSGetConsumerList \n");\r
+ printf("7. startPresence \n");\r
+ printf("8. stopPresence \n");\r
+ printf("0. Exit() \n");\r
+\r
+ printf("input : ");\r
+\r
+ scanf("%d", &num);\r
+ scanf("%c", &dummy);\r
+ fflush(stdin);\r
+\r
+ switch (num)\r
+ {\r
+ case 1:\r
+ OIC_LOG(INFO, TAG, "NSStartProvider(Accepter: Provider)");\r
+ NSStartProvider(NS_ACCEPTER_PROVIDER, subscribeRequestCallback, syncCallback);\r
+ break;\r
+ case 2:\r
+ OIC_LOG(INFO, TAG, "NSStartProvider(Accepter: Consumer)");\r
+ NSStartProvider(NS_ACCEPTER_CONSUMER, subscribeRequestCallback, syncCallback);\r
+ break;\r
+ case 3:\r
+ OIC_LOG(INFO, TAG, "NSSendNotification()");\r
+\r
+ char title[100];\r
+ char body[100];\r
+ char charID[100];\r
+\r
+ printf("id : %d\n", ++id);\r
+\r
+ printf("title : ");\r
+\r
+ gets(title);\r
+\r
+ printf("body : ");\r
+ gets(body);\r
+\r
+ printf("app - mId : %s \n", charID);\r
+ printf("app - mTitle : %s \n", title);\r
+ printf("app - mContentText : %s \n", body);\r
+\r
+ NSMessage * msg = (NSMessage *)malloc(sizeof(NSMessage));\r
+\r
+ sprintf(charID, "%d", id);\r
+\r
+ msg->mId = strdup(charID);\r
+ msg->mTitle = strdup(title);\r
+ msg->mContentText = strdup(body);\r
+\r
+ NSSendNotification(msg);\r
+\r
+ break;\r
+\r
+ case 4:\r
+ OIC_LOG(INFO, TAG, "NSRead");\r
+ NSSync * sync = (NSSync*) malloc(sizeof(NSSync));\r
+\r
+ sync->mMessageId = strdup("dev_001");\r
+ sync->mState = 1;\r
+\r
+ NSSendSync(sync);\r
+\r
+ break;\r
+/*\r
+ case 5:\r
+ OIC_LOG(INFO, TAG, "NSAccept");\r
+\r
+ NSConsumer * consumer = (NSConsumer *)malloc(sizeof(NSConsumer));\r
+ consumer->mId = strdup("dev_001");\r
+ consumer->mUserData = NULL;\r
+ bool accepted = true;\r
+\r
+ NSAccept(consumer, accepted);\r
+\r
+ break;*/\r
+\r
+ case 6:\r
+ OIC_LOG(INFO, TAG, "NSGetConsumerList");\r
+\r
+ /*\r
+ NSConsumer *list = NULL;\r
+ int numberOfList;\r
+\r
+ NSGetConsumerList(list, numberOfList);\r
+\r
+ if(list != NULL)\r
+ {\r
+ OIC_LOG(INFO, TAG, "Consumer list");\r
+ }\r
+ else\r
+ {\r
+ OIC_LOG(INFO, TAG, "No Consumer list");\r
+ }\r
+ */\r
+ break;\r
+ case 7:\r
+ OIC_LOG(INFO, TAG, "NSStartPresence");\r
+ NSTestStartPresence();\r
+ break;\r
+ case 8:\r
+ OIC_LOG(INFO, TAG, "NSStopPresence");\r
+ NSTestStopPresence();\r
+ break;\r
+ default:\r
+ OIC_LOG(INFO, TAG, "Under Construction");\r
+ break;\r
+ }\r
+\r
+ printf("\n");\r
+ }\r
+\r
+ return 0;\r
+}\r
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_COMMON_H_
+#define _NS_COMMON_H_
+
+#define NS_ATTRIBUTE_POLICY "ACCEPTER"
+#define NS_ATTRIBUTE_MESSAGE "MESSAGE_URI"
+#define NS_ATTRIBUTE_SYNC "SYNC_URI"
+#define NS_ATTRIBUTE_ACCPETANCE "ACCEPTANCE"
+#define NS_ATTRIBUTE_ID "ID"
+#define NS_ATTRIBUTE_TITLE "TITLE"
+#define NS_ATTRIBUTE_TEXT "CONTENTTEXT"
+#define NS_ATTRIBUTE_STATE "STATE"
+#define NS_ATTRIBUTE_DEVICE "DEVICE"
+
+typedef enum eResult
+{
+ NS_OK = 100,
+ NS_ERROR = 200,
+ NS_SUCCESS = 300,
+ NS_FAIL = 400,
+ NS_ALLOW = 500,
+ NS_DENY = 600,
+
+} NSResult;
+
+typedef enum eAccessPolicy
+{
+ NS_ACCEPTER_PROVIDER = 0,
+ NS_ACCEPTER_CONSUMER = 1,
+
+} NSAccessPolicy;
+
+typedef struct
+{
+ char * mId;
+ void * mUserData;
+} NSDevice;
+
+typedef NSDevice NSConsumer;
+
+typedef struct
+{
+ char * mId;
+ char * mUserData;
+ char * messageUri;
+ char * syncUri;
+} NSProvider;
+
+typedef struct
+{
+ // Mandatory
+ char * mId;
+ char * mTitle;
+
+ //Optional
+ char * mContentText;
+
+} NSMessage;
+
+typedef enum
+{
+ Notification_Read,
+ Notification_Dismiss,
+} NSSyncTypes;
+
+typedef struct
+{
+ // Mandatory
+ char * mMessageId;
+ NSSyncTypes mState;
+
+ //Optional
+ NSDevice * mDevice;
+
+} NSSync;
+
+typedef void (* NSSubscribeRequestCallback)(NSConsumer *);
+typedef void (* NSSyncCallback)(NSProvider *, NSSync *);
+
+typedef void (* NSProviderDiscoveredCallback)(NSProvider *);
+// NSMessage should deleted as user.
+typedef void (* NSNotificationReceivedCallback)(NSProvider *, NSMessage *);
+
+#endif /* _NS_COMMON_H_ */
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_INTERFACE_H_
+#define _NS_CONSUMER_INTERFACE_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include "NSCommon.h"
+
+NSResult NSStartConsumer(
+ NSProviderDiscoveredCallback discoverCb,
+ NSNotificationReceivedCallback postCb,
+ NSSyncCallback syncCb);
+
+NSResult NSStopConsumer();
+
+NSResult NSRead(NSMessage *);
+
+NSResult NSDismiss(NSMessage *);
+
+NSResult NSSubscribeProvider(NSProvider *);
+
+NSResult NSUnsubscribeProvider(NSProvider *);
+
+NSResult NSRescanProvider();
+
+NSResult NSDropNSObject(NSMessage *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_INTERFACE_H_
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_INTERFACE_H_\r
+#define _NS_PROVIDER_INTERFACE_H_\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif // __cplusplus\r
+\r
+#include "NSCommon.h"\r
+#include <stdbool.h>\r
+#include <stdint.h>\r
+\r
+NSResult NSStartProvider(NSAccessPolicy policy, NSSubscribeRequestCallback subscribeRequestCb,\r
+ NSSyncCallback syncCb);\r
+\r
+NSResult NSStopProvider();\r
+\r
+NSResult NSSendNotification(NSMessage *msg);\r
+\r
+NSResult NSReadCheck(NSMessage *msg);\r
+\r
+NSResult NSAccept(NSConsumer *consumer, bool accepted);\r
+\r
+NSResult NSGetConsumerList(uint8_t *list, uint32_t size);\r
+\r
+NSResult NSTestStartPresence();\r
+\r
+NSResult NSTestStopPresence();\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif // __cplusplus\r
+\r
+#endif /* _NS_PROVIDER_INTERFACE_H_ */\r
+\r
+++ /dev/null
-Initial commit for folder structure
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSTANTS_H_
+#define _NS_CONSTANTS_H_
+
+#define NS_TAG "IOT_NOTI"
+
+// SCHEDULE //
+#define THREAD_COUNT 4
+
+// NOTIOBJ //
+#define NOTIOBJ_TITLE_KEY "title"
+#define NOTIOBJ_ID_KEY "id"
+#define NOTOOBJ_CONTENT_KEY "contentText"
+
+#define DISCOVERY_TAG "NS_PROVIDER_DISCOVERY"
+#define SUBSCRIPTION_TAG "NS_PROVIDER_SUBSCRIPTION"
+#define INTERFACE_TAG "NS_PROVIDER_INTERFACE"
+#define NOTIFICATION_TAG "NS_PROVIDER_NOTIFICATION"
+#define SCHEDULER_TAG "NS_PROVIDER_SCHEDULER"
+#define LISTENER_TAG "NS_PROVIDER_LISTENER"
+#define RESOURCE_TAG "NS_PROVIDER_RESOURCE"
+
+typedef enum eConnectionState
+{
+ DISCONNECTED = 0,
+ CONNECTED = 1,
+
+} NSConnectionState;
+
+typedef enum eSchedulerType
+{
+ RESPONSE_SCHEDULER = 0,
+ DISCOVERY_SCHEDULER = 1,
+ SUBSCRIPTION_SCHEDULER = 2,
+ NOTIFICATION_SCHEDULER = 3,
+} NSSchedulerType;
+
+
+typedef enum eTaskType
+{
+ TASK_REGISTER_RESOURCE = 1000,
+
+ TASK_START_PRESENCE = 2000,
+ TASK_STOP_PRESENCE = 2001,
+
+ TASK_RECV_SUBSCRIPTION = 3000,
+ TASK_RECV_UNSUBSCRIPTION = 3001,
+ TASK_SEND_POLICY = 3002,
+ TASK_SEND_ALLOW = 3003,
+ TASK_SEND_DENY = 3004,
+ TASK_SYNC_SUBSCRIPTION = 3005,
+
+ TASK_SEND_NOTIFICATION = 4000,
+ TASK_SEND_PENDING_NOTI = 4001,
+
+ TASK_RECV_READ = 5000,
+ TASK_RECV_DISMISS = 5001,
+ TASK_SEND_READ = 5002,
+ TASK_SEND_DISMISS = 5003,
+
+ TASK_CONSUMER_REQ_DISCOVER = 8001,
+ TASK_CONSUMER_REQ_SUBSCRIBE = 8002,
+ TASK_CONSUMER_REQ_SUBSCRIBE_CANCEL = 8003,
+ TASK_CONSUMER_RECV_NOTIFICATION = 8101,
+
+ TASK_EVENT_CONNECTED = 9000,
+ TASK_EVENT_DISCONNECTED = 9001,
+
+ TASK_CB_SUBSCRIPTION = 10000,
+ TASK_CB_SYNC = 10001,
+
+} NSTaskType;
+
+typedef enum eCache
+{
+ NS_CONSUMER_BLACKLIST = 0,
+ NS_CONSUMER_WHITELIST = 1,
+
+} NSCache;
+
+#endif /* _NS_CONSTANTS_H_ */
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include "NSQueueScheduler.h"\r
+\r
+pthread_t NSThread[THREAD_COUNT];\r
+pthread_mutex_t NSMutex[THREAD_COUNT];\r
+sem_t NSSemaphore[THREAD_COUNT];\r
+bool NSIsRunning[THREAD_COUNT] =\r
+{ false, };\r
+\r
+NSTask* NSHeadMsg[THREAD_COUNT] =\r
+{ 0, };\r
+NSTask* NSTailMsg[THREAD_COUNT] =\r
+{ 0, };\r
+\r
+void * NSResponseSchedule(void *ptr);\r
+void * NSDiscoverySchedule(void *ptr);\r
+void * NSSubScriptionSchedule(void *ptr);\r
+void * NSNotificationSchedule(void *ptr);\r
+\r
+bool NSInitScheduler()\r
+{\r
+ OIC_LOG(INFO, SCHEDULER_TAG, "NSInitScheduler()");\r
+\r
+ int i = 0;\r
+ // NsQsStopScheduler(ALL_SCHEDULER);\r
+\r
+ for (i = 0; i < THREAD_COUNT; i++)\r
+ {\r
+ pthread_mutex_init(&NSMutex[i], NULL);\r
+ NSIsRunning[i] = true;\r
+ sem_init(&(NSSemaphore[i]), 0, 0);\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+bool NSStartScheduler()\r
+{\r
+ int i = 0;\r
+\r
+ for (i = 0; i < THREAD_COUNT; i++)\r
+ {\r
+ pthread_mutex_lock(&NSMutex[i]);\r
+\r
+ switch (i)\r
+ {\r
+ case RESPONSE_SCHEDULER:\r
+ {\r
+ pthread_create(&NSThread[i], NULL, NSResponseSchedule, NULL);\r
+ }\r
+ break;\r
+\r
+ case DISCOVERY_SCHEDULER:\r
+ {\r
+ pthread_create(&NSThread[i], NULL, NSDiscoverySchedule, NULL);\r
+ }\r
+ break;\r
+\r
+ case SUBSCRIPTION_SCHEDULER:\r
+ {\r
+ pthread_create(&NSThread[i], NULL, NSSubScriptionSchedule, NULL);\r
+ }\r
+ break;\r
+\r
+ case NOTIFICATION_SCHEDULER:\r
+ {\r
+ pthread_create(&NSThread[i], NULL, NSNotificationSchedule, NULL);\r
+ }\r
+ break;\r
+\r
+ default:\r
+ break;\r
+\r
+ }\r
+\r
+ NSHeadMsg[i] = NSTailMsg[i] = NULL;\r
+\r
+ pthread_mutex_unlock(&NSMutex[i]);\r
+\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+bool NSStopScheduler()\r
+{\r
+ int i = 0;\r
+\r
+ for (i = THREAD_COUNT - 1; i >= 0; --i)\r
+ {\r
+\r
+ NSIsRunning[i] = false;\r
+\r
+ pthread_join(NSThread[i], (void *) NULL);\r
+ NSThread[i] = 0;\r
+\r
+ pthread_mutex_lock(&NSMutex[i]);\r
+\r
+ while (NSHeadMsg[i]->nextTask != NULL)\r
+ {\r
+ NSTask* temp = NSHeadMsg[i];\r
+ NSHeadMsg[i] = NSHeadMsg[i]->nextTask;\r
+ OICFree(temp);\r
+ }\r
+\r
+ OICFree(NSHeadMsg[i]);\r
+\r
+ pthread_mutex_unlock(&NSMutex[i]);\r
+ }\r
+\r
+ return true;\r
+}\r
+\r
+void NSPushQueue(NSSchedulerType schedulerType, NSTaskType taskType, void* data)\r
+{\r
+ pthread_mutex_lock(&NSMutex[schedulerType]);\r
+ // mutext Lock\r
+ if (NSHeadMsg[schedulerType] == NULL)\r
+ {\r
+ printf("first schedule");\r
+ NSHeadMsg[schedulerType] = (NSTask*) malloc(sizeof(NSTask));\r
+ memset(NSHeadMsg[schedulerType], 0, sizeof(NSTask));\r
+ NSHeadMsg[schedulerType]->taskType = taskType;\r
+ NSHeadMsg[schedulerType]->taskData = data;\r
+ NSHeadMsg[schedulerType]->nextTask = NULL;\r
+ NSTailMsg[schedulerType] = NSHeadMsg[schedulerType];\r
+ }\r
+ else\r
+ {\r
+ printf("after first schedule");\r
+ NSTask* newNode = (NSTask*) malloc(sizeof(NSTask));\r
+ memset(newNode, 0, sizeof(NSTask));\r
+ newNode->taskType = taskType;\r
+ newNode->taskData = data;\r
+ newNode->nextTask = NULL;\r
+\r
+ NSTailMsg[schedulerType]->nextTask = newNode;\r
+ NSTailMsg[schedulerType] = newNode;\r
+ }\r
+\r
+ sem_post(&(NSSemaphore[schedulerType]));\r
+ pthread_mutex_unlock(&NSMutex[schedulerType]);\r
+\r
+ // mutext UnLock\r
+}\r
+\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _QUEUE_SCHEDULER_H_\r
+#define _QUEUE_SCHEDULER_H_\r
+\r
+#include <stdio.h>\r
+#include <pthread.h>\r
+#include <semaphore.h>\r
+#include <oic_malloc.h>\r
+#include <stdbool.h>\r
+#include "ocstack.h"\r
+#include "NSCommon.h"\r
+#include "NSConstants.h"\r
+#include "NSStructs.h"\r
+#include "logger.h"\r
+\r
+extern NSTask* NSHeadMsg[THREAD_COUNT]; // Current MSG;\r
+extern NSTask* NSTailMsg[THREAD_COUNT]; // Recently MSG;\r
+\r
+extern pthread_t NSThread[THREAD_COUNT];\r
+extern pthread_mutex_t NSMutex[THREAD_COUNT];\r
+extern sem_t NSSemaphore[THREAD_COUNT];\r
+extern bool NSIsRunning[THREAD_COUNT];\r
+\r
+extern void * NSResponseSchedule(void *ptr);\r
+extern void * NSDiscoverySchedule(void *ptr);\r
+extern void * NSSubScriptionSchedule(void *ptr);\r
+extern void * NSNotificationSchedule(void *ptr);\r
+\r
+bool NSInitScheduler();\r
+bool NSStartScheduler();\r
+bool NSStopScheduler();\r
+void NSPushQueue(NSSchedulerType, NSTaskType, void*);\r
+\r
+#endif /* _QUEUE_SCHEDULER_H_ */\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_STRUCTS_H_\r
+#define _NS_STRUCTS_H_\r
+\r
+#include <string.h>\r
+#include <stdlib.h>\r
+#include "NSCommon.h"\r
+#include "NSConstants.h"\r
+\r
+typedef struct _nsTask\r
+{\r
+ NSTaskType taskType;\r
+ void* taskData;\r
+ struct _nsTask* nextTask;\r
+} NSTask;\r
+\r
+#endif /* _NS_STRUCTS_H_ */\r
+++ /dev/null
-Initial commit for folder structure
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerCache.h"
+#include "NSConsumerCommon.h"
+
+#include "stdlib.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+NSCacheList * NSConsumerCacheInit()
+{
+ NSCacheList * retNSCacheList = (NSCacheList *)OICMalloc(sizeof(NSCacheList));
+ if (!retNSCacheList)
+ {
+ return NULL;
+ }
+
+ retNSCacheList->head = NULL;
+ retNSCacheList->last = NULL;
+
+ return retNSCacheList;
+}
+
+NSResult NSConsumerCacheDestroy(NSCacheList * list)
+{
+ NSCacheObject * iter = list->head;
+
+ NSCacheObject * next = NULL;
+ while (iter)
+ {
+ next = (NSCacheObject *)iter->next;
+ if (NS_OK != NSConsumerCacheDelete(list, iter))
+ {
+ return NS_ERROR;
+ }
+ iter = next;
+ }
+
+ OICFree((NSCacheList *) list);
+
+ return NS_OK;
+}
+
+NSResult NSConsumerCacheInsert(NSCacheList * list, NSCacheObject * newObj)
+{
+ NSCacheObject * obj = (NSCacheObject *)OICMalloc(sizeof(NSCacheObject));
+ if (!obj)
+ {
+ NS_CONSUMER_LOG(ERROR, "Fail to Create New Object");
+ return NS_ERROR;
+ }
+
+ NSMessage_consumer * msgObj = (NSMessage_consumer *) OICMalloc(sizeof(NSMessage_consumer));
+ NSMessage_consumer * newMsgObj = (NSMessage_consumer *) newObj->data;
+
+ NS_CONSUMER_LOG_V(DEBUG, "Title: %s", newMsgObj->mTitle);
+ NS_CONSUMER_LOG_V(DEBUG, "ID: %s", newMsgObj->mId);
+ NS_CONSUMER_LOG_V(DEBUG, "TEXT: %s", newMsgObj->mContentText);
+
+ msgObj->mTitle = OICStrdup(newMsgObj->mTitle);
+ msgObj->mId = OICStrdup(newMsgObj->mId);
+ msgObj->mContentText = OICStrdup(newMsgObj->mContentText);
+
+ if (!msgObj->mId)
+ {
+ NS_CONSUMER_LOG(ERROR, "Notification Attributes copy fail");
+ }
+
+ msgObj->addr = (OCDevAddr *)OICMalloc(sizeof(OCDevAddr));
+ if (!msgObj->addr)
+ {
+ NS_CONSUMER_LOG(ERROR, "OCDevAddr allocation is failed.");
+ }
+
+ memcpy(msgObj->addr, newMsgObj->addr, sizeof(OCDevAddr));
+ msgObj->type = newMsgObj->type;
+
+ //obj->data = (NSCacheData *)OICMalloc(sizeof(NSCacheData));
+ obj->data = (NSCacheData *) msgObj;
+ //memcpy(obj->data, (NSCacheData *)msgObj, sizeof(NSCacheData));
+ obj->next = NULL;
+
+ msgObj = NULL;
+ msgObj = (NSMessage_consumer *) obj->data;
+
+ if (!list->head)
+ {
+ list->head = obj;
+ return NS_OK;
+ }
+
+ NSCacheObject * iter = list->head;
+ while (iter)
+ {
+ if (iter == obj)
+ {
+ return NS_ERROR;
+ }
+ iter = (NSCacheObject *) iter->next;
+ }
+
+ if (list->last)
+ {
+ (list->last)->next = obj;
+ }
+
+ list->last = obj;
+
+ return NS_OK;
+}
+
+NSResult NSConsumerCacheDelete(NSCacheList * list, NSCacheObject * delObj) // Free?
+{
+ NSCacheObject * beDelete;
+ if (list->head == delObj)
+ {
+ beDelete = list->head;
+ list->head = (NSCacheObject *) list->head->next;
+ return NS_OK;
+ }
+
+ NSCacheObject * pre = list->head;
+ beDelete = (NSCacheObject *) pre->next;
+ while (beDelete)
+ {
+ if (beDelete == delObj)
+ {
+ if (beDelete == list->last)
+ {
+ pre->next = NULL;
+ list->last = pre;
+ }
+ else
+ {
+ pre->next = beDelete->next;
+ }
+ OICFree((NSCacheObject *) beDelete);
+ break;
+ }
+ pre = beDelete;
+ beDelete = (NSCacheObject *) beDelete->next;
+ }
+
+ return NS_OK;
+}
+
+NSCacheObject * NSConsumerCacheFind(NSCacheList * list, char * findId)
+{
+
+ NS_CONSUMER_LOG_V(DEBUG, "findID: %s", findId);
+ NSCacheObject * retObj = list->head;
+ if (!retObj)
+ {
+ NS_CONSUMER_LOG(DEBUG, "findcache is null");
+ return retObj;
+ }
+
+ NSMessage_consumer * obj = (NSMessage_consumer *) retObj->data;
+ NS_CONSUMER_LOG_V(DEBUG, "objmID: %s", obj->mId);
+
+ while (retObj)
+ {
+ NSMessage_consumer * obj = (NSMessage_consumer *) retObj->data;
+ NS_CONSUMER_LOG_V(DEBUG, "objmID: %s", obj->mId);
+ if (!strcmp(obj->mId, findId))
+ {
+ return retObj;
+ }
+ retObj = (NSCacheObject *) retObj->next;
+ }
+
+ return retObj;
+}
+
+NSResult NSConsumerCacheWrite(NSCacheList * list, NSCacheObject * writeObj)
+{
+ NSCacheObject * beModify = NSConsumerCacheFind(list, ((NSMessage_consumer *) writeObj->data)->mId);
+ if (!beModify)
+ {
+ return NS_ERROR;
+ }
+
+ NSMessage_consumer * msgObj = (NSMessage_consumer *) beModify->data;
+ NSMessage_consumer * msgWriteObj = (NSMessage_consumer *) writeObj->data;
+
+ if (msgWriteObj->mId)
+ {
+ strcpy(msgObj->mId, msgWriteObj->mId);
+ }
+ if (msgWriteObj->mTitle)
+ {
+ strcpy(msgObj->mTitle, msgWriteObj->mTitle);
+ }
+ if (msgWriteObj->mContentText)
+ {
+ strcpy(msgObj->mContentText, msgWriteObj->mContentText);
+ }
+
+ memcpy(msgObj->addr, msgWriteObj->addr, sizeof(OCDevAddr));
+ msgObj->type = msgWriteObj->type;
+
+ return NS_OK;
+}
+
+NSCacheObject * NSConsumerCacheRead(NSCacheList * list, NSCacheObject * readObj)
+{
+ NSCacheObject * retObj = NSConsumerCacheFind(list, ((NSMessage_consumer *) readObj->data)->mId);
+ if (!retObj)
+ {
+ return NULL;
+ }
+
+ return retObj;
+}
+
+
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_CACHE_H_
+#define _NS_CONSUMER_CACHE_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include "NSCommon.h"
+#include "NSConsumerCommon.h"
+
+
+typedef void * NSCacheData;
+
+typedef struct _NSCacheObject
+{
+ NSCacheData * data;
+ struct _NSCacheObject * next;
+} NSCacheObject;
+
+typedef struct
+{
+ NSCacheObject * head;
+ NSCacheObject * last;
+} NSCacheList;
+
+NSCacheList * NSConsumerCacheInit();
+NSResult NSConsumerCacheDestroy(NSCacheList * list);
+
+NSResult NSConsumerCacheInsert(NSCacheList * list, NSCacheObject * newObj);
+NSResult NSConsumerCacheDelete(NSCacheList * list, NSCacheObject * delObj);
+
+NSCacheObject * NSConsumerCacheFind(NSCacheList * list, char * findId);
+
+NSResult NSConsumerCacheWrite(NSCacheList * list, NSCacheObject * writeObj);
+NSCacheObject * NSConsumerCacheRead(NSCacheList * list, NSCacheObject * readObj);
+
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_CACHE_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerCommon.h"
+#include "NSThread.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+
+bool * NSGetBoneIsStartedConsumer()
+{
+ static bool g_isStartedConsumer = false;
+
+ return & g_isStartedConsumer;
+}
+
+void NSSetIsStartedConsumer(bool setValue)
+{
+ * NSGetBoneIsStartedConsumer() = setValue;
+}
+
+bool NSIsStartedConsumer()
+{
+ return * NSGetBoneIsStartedConsumer();
+}
+
+NSProviderDiscoveredCallback * NSGetBoneDiscoverCb()
+{
+ static NSProviderDiscoveredCallback g_discoverCb = NULL;
+
+ return & g_discoverCb;
+}
+
+void NSSetDiscoverProviderCb(NSProviderDiscoveredCallback cb)
+{
+ * NSGetBoneDiscoverCb() = cb;
+}
+
+NSProviderDiscoveredCallback NSGetDiscoverCb()
+{
+ return * NSGetBoneDiscoverCb();
+}
+
+void * NSDiscoverdProviderFunc(void * provider)
+{
+ NSGetDiscoverCb()((NSProvider *) provider);
+
+ return NULL;
+}
+
+void NSDiscoveredProvider(NSProvider * provider)
+{
+ if (!NSThreadInit(NSDiscoverdProviderFunc, (void *) provider))
+ {
+ NS_CONSUMER_LOG(ERROR, "execute discovered provider callback fail");
+ return;
+ }
+}
+
+NSSyncCallback * NSGetBoneNotificationSyncCb()
+{
+ static NSSyncCallback g_syncCb = NULL;
+
+ return & g_syncCb;
+}
+
+void NSSetNotificationSyncCb(NSSyncCallback cb)
+{
+ * NSGetBoneNotificationSyncCb() = cb;
+}
+
+typedef struct
+{
+ NSProvider * provider;
+ NSSync * sync;
+} NSSyncData;
+
+void * NSNotificationSyncFunc(void * obj)
+{
+ NSProvider * provider = ((NSSyncData *) obj)->provider;
+ NSSync * syncData = ((NSSyncData *) obj)->sync;
+ (* NSGetBoneNotificationSyncCb())(provider, syncData);
+ return NULL;
+}
+
+void NSNotificationSync(NSProvider * provider, NSSync * sync)
+{
+ NSSyncData * obj = (NSSyncData *)OICMalloc(sizeof(NSSyncData));
+ obj->provider = provider;
+ obj->sync = sync;
+
+ if (!NSThreadInit(NSNotificationSyncFunc, (void *) obj))
+ {
+ NS_CONSUMER_LOG(ERROR, "execute noti post callback fail");
+ return;
+ }
+}
+
+NSNotificationReceivedCallback * NSGetBoneNotificationPostedCb()
+{
+ static NSNotificationReceivedCallback g_postCb = NULL;
+
+ return & g_postCb;
+}
+
+void NSSetNotificationPostedCb(NSNotificationReceivedCallback cb)
+{
+ * NSGetBoneNotificationPostedCb() = cb;
+}
+
+NSNotificationReceivedCallback NSGetNotificationPostedCb()
+{
+ return * NSGetBoneNotificationPostedCb();
+}
+
+typedef struct
+{
+ NSProvider * provider;
+ NSMessage * msg;
+} NSMessageData;
+
+void * NSNotificationPostFunc(void * obj)
+{
+ NSMessageData * msgData = (NSMessageData *) obj;
+
+ NSGetNotificationPostedCb()((NSProvider *) msgData->provider,
+ (NSMessage *) msgData->msg);
+ return NULL;
+}
+
+void NSNotificationPost(NSProvider * provider, NSMessage * msg)
+{
+ NSMessageData * obj = (NSMessageData *)OICMalloc(sizeof(NSMessageData));
+ if (!obj)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSMessageData allocation is failed");
+ return;
+ }
+ obj->provider = provider;
+ obj->msg = msg;
+
+ if (!NSThreadInit(NSNotificationPostFunc, (void *) obj))
+ {
+ NS_CONSUMER_LOG(ERROR, "execute noti post callback fail");
+ return;
+ }
+}
+
+onRIResponseListener * NSGetBoneResponseListener()
+{
+ static onRIResponseListener g_responseCb = NULL;
+
+ return & g_responseCb;
+}
+
+void NSSetResponseListener(onRIResponseListener cb)
+{
+ * NSGetBoneResponseListener() = cb;
+}
+
+onRIResponseListener NSGetResponseListener()
+{
+ return * NSGetBoneResponseListener();
+}
+
+NSTask * NSMakeTask(NSTaskType type, void * data)
+{
+ NSTask * retTask = OICMalloc(sizeof(NSTask));
+ if (!retTask)
+ {
+ return NULL;
+ }
+
+ retTask->taskType = type;
+ retTask->taskData = data;
+ retTask->nextTask = NULL;
+
+ return retTask;
+}
+
+NSMessage_consumer * NSCopyMessage(NSMessage_consumer * msg)
+{
+ if (!msg)
+ {
+ return NULL;
+ }
+
+ NSMessage_consumer * newMsg = (NSMessage_consumer *)OICMalloc(sizeof(NSMessage_consumer));
+ if (!newMsg)
+ {
+ return NULL;
+ }
+
+ newMsg->mId = OICStrdup(msg->mId);
+ newMsg->mTitle = OICStrdup(msg->mTitle);
+ newMsg->mContentText = OICStrdup(msg->mContentText);
+ newMsg->addr = (OCDevAddr *)OICMalloc(sizeof(OCDevAddr));
+ if (!newMsg->addr)
+ {
+ NS_CONSUMER_LOG(ERROR, "OCDevAddr allocation is failed");
+ }
+ memcpy(newMsg->addr, msg->addr, sizeof(OCDevAddr));
+
+ return newMsg;
+}
+void NSRemoveMessage(NSMessage_consumer * msg)
+{
+ if (msg->mId)
+ {
+ OICFree(msg->mId);
+ msg->mId = NULL;
+ }
+ if (msg->mTitle)
+ {
+ OICFree(msg->mTitle);
+ msg->mTitle = NULL;
+ }
+ if (msg->mContentText)
+ {
+ OICFree(msg->mContentText);
+ msg->mContentText = NULL;
+ }
+ if (msg->addr)
+ {
+ OICFree(msg->addr);
+ msg->addr = NULL;
+ }
+
+ OICFree(msg);
+ msg = NULL;
+}
+
+OCStackResult NSRequestToResourceIntrospection(OCDoHandle * handle,
+ OCMethod method, const OCDevAddr * addr,
+ const char * queryUrl, OCPayload * payload, void * callback)
+{
+ OCCallbackData cbdata;
+
+ cbdata.cb = NSGetResponseListener();
+ cbdata.context = callback;
+ cbdata.cd = NULL;
+
+ return OCDoResource(handle, method, queryUrl, addr,
+ payload, CT_DEFAULT, NS_QOS, &cbdata, NULL, 0);
+}
+
+const char * NS_CONVERT_LEVEL(int level)
+{
+ return ((level) == 0) ? "DEBUG" :
+ ((level) == 1) ? "INFO" :
+ ((level) == 2) ? "WARNING" :
+ ((level) == 3) ? "ERROR" : "FATAL";
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_CONSTANTS_H_
+#define _NS_CONSUMER_CONSTANTS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdio.h>
+#include <stdbool.h>
+
+#include "NSCommon.h"
+#include "NSStructs.h"
+#include "ocstack.h"
+
+#define NS_LOG_PRINTF 0
+
+#define __NS_FILE__ ( strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__ )
+
+const char * NS_CONVERT_LEVEL(int level);
+
+// TODO fix ns log using oic log.
+#ifdef TB_LOG
+#include "logger.h"
+#define NS_CONSUMER_LOG_V(level, format, ...) (OIC_LOG_V((level), __NS_FILE__, (format), __VA_ARGS__))
+#define NS_CONSUMER_LOG(level, msg) (OIC_LOG((level), __NS_FILE__, (msg)))
+#else
+#include "logger.h"
+#define NS_CONSUMER_LOG_V(level, format, ...) { \
+ printf("%s: %s ", NS_CONVERT_LEVEL(level), __NS_FILE__); \
+ printf((format), __VA_ARGS__); \
+ printf("\n"); }
+#define NS_CONSUMER_LOG(level, msg) { \
+ printf("%s: %s ", NS_CONVERT_LEVEL(level), __NS_FILE__); \
+ printf((msg)); \
+ printf("\n"); }
+
+#endif
+
+#define NS_QOS OC_LOW_QOS
+#define NS_RESOURCE_TYPE "oic.r.notification"
+#define NS_RESOURCE_URI "/notification"
+#define NS_INTERFACE_BASELINE "oic.if.baseline"
+#define NS_INTERFACE_NOTIFICATION "oic.if.notification"
+#define NS_RESOURCE_QUERY "/oic/res"
+
+#define NS_DISCOVER_QUERY "/oic/res?rt=oic.r.notification"
+
+typedef OCStackApplicationResult (*onRIResponseListener)(
+ void *, OCDoHandle, OCClientResponse *);
+
+typedef enum
+{
+ Read,
+ Dismiss,
+ Notification,
+} NSConsumerMessageTypes;
+
+typedef struct
+{
+ // Mandatory
+ char * mId;
+ char * mTitle;
+
+ //Optional
+ char * mContentText;
+
+ OCDevAddr * addr;
+ char * syncUri;
+ NSConsumerMessageTypes type;
+} NSMessage_consumer;
+
+bool NSIsStartedConsumer();
+void NSSetIsStartedConsumer(bool setValue);
+
+void NSSetDiscoverProviderCb(NSProviderDiscoveredCallback cb);
+void NSDiscoveredProvider(NSProvider * handle);
+
+void NSSetNotificationPostedCb(NSNotificationReceivedCallback cb);
+void NSNotificationPost(NSProvider * provider, NSMessage * obj);
+
+void NSSetNotificationSyncCb(NSSyncCallback cb);
+void NSNotificationSync(NSProvider * provider, NSSync * sync);
+
+onRIResponseListener NSGetResponseListener();
+void NSSetResponseListener(onRIResponseListener cb);
+
+NSTask * NSMakeTask(NSTaskType, void *);
+
+NSResult NSConsumerPushEvent(NSTask *);
+
+NSMessage_consumer * NSCopyMessage(NSMessage_consumer *);
+void NSRemoveMessage(NSMessage_consumer *);
+
+OCStackResult NSRequestToResourceIntrospection(OCDoHandle * handle,
+ OCMethod method, const OCDevAddr * addr,
+ const char * queryUrl, OCPayload * payload, void * callback);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_CONSTANTS_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerDiscovery.h"
+
+#include <string.h>
+#include "NSCommon.h"
+#include "NSConsumerCommon.h"
+#include "ocpayload.h"
+#include "oic_malloc.h"
+
+#define NS_PAYLOAD_KEY_ACCEPTER "ACCEPTER"
+#define NS_DISCOVER_QUERY "/oic/res?rt=oic.r.notification"
+#define NS_PRESENCE_SUBSCRIBE_QUERY "coap://224.0.1.187:5683/oic/ad?rt=oic.r.notification"
+#define NS_GET_INFORMATION_QUERY "/notification?if=oic.if.notification"
+
+OCDoHandle * getPresenceHandle()
+{
+ static OCDoHandle * g_PresenceHandle = NULL;
+
+ return g_PresenceHandle;
+}
+
+OCStackApplicationResult NSConsumerPresenceListener(
+ OCDoHandle handle, OCClientResponse * clientResponse)
+{
+ (void) handle;
+ NS_CONSUMER_LOG_V(DEBUG, "Presence income : %s:%d",
+ clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ NS_CONSUMER_LOG_V(DEBUG, "Presence result : %d",
+ clientResponse->result);
+ NS_CONSUMER_LOG_V(DEBUG, "Presence sequenceNum : %d",
+ clientResponse->sequenceNumber);
+
+ if (!NSIsStartedConsumer())
+ {
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OCPresencePayload * payload = (OCPresencePayload *)clientResponse->payload;
+ if (payload->trigger == OC_PRESENCE_TRIGGER_DELETE ||
+ clientResponse->result == OC_STACK_PRESENCE_STOPPED)
+ {
+ // TODO find request and cancel
+ NS_CONSUMER_LOG(DEBUG, "stopped presence or resource is deleted.");
+ //OCCancel(handle, NS_QOS, NULL, 0);
+ }
+
+ else if (payload->trigger == OC_PRESENCE_TRIGGER_CREATE)
+ {
+ NSRequestToResourceIntrospection(NULL, OC_REST_DISCOVER, clientResponse->addr,
+ NS_DISCOVER_QUERY, NULL, NSProviderDiscoverListener);
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackApplicationResult NSProviderDiscoverListener(
+ OCDoHandle handle, OCClientResponse * clientResponse)
+{
+ (void) handle;
+ NS_CONSUMER_LOG_V(DEBUG, "Discover income : %s:%d",
+ clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ NS_CONSUMER_LOG_V(DEBUG, "Discover result : %d",
+ clientResponse->result);
+ NS_CONSUMER_LOG_V(DEBUG, "Discover sequenceNum : %d",
+ clientResponse->sequenceNumber);
+
+ if (!NSIsStartedConsumer())
+ {
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ if (!clientResponse->payload)
+ {
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ OCResourcePayload * resource = ((OCDiscoveryPayload *)clientResponse->payload)->resources;
+ while (resource)
+ {
+ if (!strcmp(resource->uri, NS_RESOURCE_URI))
+ {
+ NSRequestToResourceIntrospection(
+ NULL, OC_REST_GET, clientResponse->addr,
+ NS_RESOURCE_URI, NULL, NSGetProviderInformation);
+ }
+ resource = resource->next;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackApplicationResult NSGetProviderInformation(
+ OCDoHandle handle, OCClientResponse * clientResponse)
+{
+ (void) handle;
+ int64_t accepter = 0;
+
+ NS_CONSUMER_LOG_V(DEBUG, "GET response income : %s:%d",
+ clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ NS_CONSUMER_LOG_V(DEBUG, "GET response result : %d",
+ clientResponse->result);
+ NS_CONSUMER_LOG_V(DEBUG, "GET response sequenceNum : %d",
+ clientResponse->sequenceNumber);
+ NS_CONSUMER_LOG_V(DEBUG, "GET response resource uri : %s",
+ clientResponse->resourceUri);
+
+ if (!NSIsStartedConsumer())
+ {
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ if (!clientResponse->payload)
+ {
+ NS_CONSUMER_LOG(ERROR, "payload is null");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ if (!OCRepPayloadGetPropInt((OCRepPayload *)clientResponse->payload,
+ NS_PAYLOAD_KEY_ACCEPTER, & accepter))
+ {
+ NS_CONSUMER_LOG(ERROR, "can not seach for accepter");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ NSProvider * newProvider = (NSProvider *)OICMalloc(sizeof(NSProvider));
+ if (!newProvider)
+ {
+ NS_CONSUMER_LOG(DEBUG, "NSProvider allocation fail");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ // TODO set id
+ newProvider->mId = NULL;
+ newProvider->mUserData = (void *)OICMalloc(sizeof(OCDevAddr));
+ if (!newProvider)
+ {
+ NS_CONSUMER_LOG(DEBUG, "OCDevAddr allocation fail");
+ OICFree(newProvider);
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+ memcpy(newProvider->mUserData, clientResponse->addr, sizeof(OCDevAddr));
+
+ {
+ OCRepPayload * payload = (OCRepPayload *)clientResponse->payload;
+ while (payload)
+ {
+ NS_CONSUMER_LOG_V(DEBUG, "Payload Key : %s", payload->values->name);
+ payload = payload->next;
+ }
+ }
+
+ if (!OCRepPayloadGetPropString((OCRepPayload *)clientResponse->payload,
+ "MESSAGE_URI", & newProvider->messageUri))
+ {
+ OICFree(newProvider->mUserData);
+ OICFree(newProvider);
+ NS_CONSUMER_LOG(ERROR, "can not seach for message uri");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ if (!OCRepPayloadGetPropString((OCRepPayload *)clientResponse->payload,
+ NS_ATTRIBUTE_SYNC, & newProvider->syncUri))
+ {
+ OICFree(newProvider->messageUri);
+ OICFree(newProvider->mUserData);
+ OICFree(newProvider);
+ NS_CONSUMER_LOG(ERROR, "can not seach for sync uri");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ if (accepter == NS_ACCEPTER_CONSUMER)
+ {
+ NS_CONSUMER_LOG(DEBUG, "accepter is NS_ACCEPTER_CONSUMER, Callback to user");
+
+ NSDiscoveredProvider(newProvider);
+ }
+ else
+ {
+ NS_CONSUMER_LOG(DEBUG, "accepter is NS_ACCEPTER_PROVIDER, request subscribe");
+
+ NSTask * task = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE, (void *) newProvider);
+ if (!task)
+ {
+ NS_CONSUMER_LOG(DEBUG, "NSTask allocation fail");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ NSConsumerPushEvent(task);
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+void NSConsumerDiscoveryHandleMsg(NSTask * task)
+{
+ if (!task)
+ {
+ NS_CONSUMER_LOG(ERROR, "task is null");
+ return;
+ }
+
+ NS_CONSUMER_LOG_V(DEBUG, "Receive Event : %d", (int)task->taskType);
+ if (task->taskType == TASK_EVENT_CONNECTED || task->taskType == TASK_CONSUMER_REQ_DISCOVER)
+ {
+ NSRequestToResourceIntrospection(NULL, OC_REST_DISCOVER, NULL, NS_DISCOVER_QUERY,
+ NULL, NSProviderDiscoverListener);
+ }
+ else
+ {
+ NS_CONSUMER_LOG(ERROR, "Unknown type message");
+ }
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_DISCOVERY_H_
+#define _NS_CONSUMER_DISCOVERY_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdlib.h>
+
+#include "ocstack.h"
+#include "NSStructs.h"
+
+void NSConsumerDiscoveryHandleMsg(NSTask *);
+
+OCStackApplicationResult NSConsumerPresenceListener(OCDoHandle, OCClientResponse *);
+
+// for discover result
+OCStackApplicationResult NSProviderDiscoverListener(OCDoHandle, OCClientResponse *);
+
+// for checking Permission
+OCStackApplicationResult NSGetProviderInformation(OCDoHandle, OCClientResponse *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_DISCOVERY_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerInterface.h"
+
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include "NSCommon.h"
+#include "NSConsumerCommon.h"
+#include "NSConsumerMessageHandler.h"
+#include "oic_malloc.h"
+
+// Public APIs
+NSResult NSStartConsumer(
+ NSProviderDiscoveredCallback discoverCb,
+ NSNotificationReceivedCallback postCb,
+ NSSyncCallback syncCb)
+{
+ if (NSIsStartedConsumer())
+ {
+ printf("is already started consumer service?\n");
+ return NS_OK;
+ }
+
+ NSSetDiscoverProviderCb(discoverCb);
+ NSSetNotificationPostedCb(postCb);
+ NSSetNotificationSyncCb(syncCb);
+ NSSetIsStartedConsumer(true);
+
+ if (NS_OK != NSConsumerMessageHandlerInit())
+ {
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+NSResult NSStopConsumer()
+{
+ NSSetDiscoverProviderCb(NULL);
+ NSSetNotificationPostedCb(NULL);
+ NSSetNotificationSyncCb(NULL);
+ NSSetIsStartedConsumer(false);
+
+ return NS_OK;
+}
+
+NSResult NSSubscribeProvider(NSProvider * provider)
+{
+ NSTask * subscribeTask = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE, (void *) provider);
+ if (!subscribeTask)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail");
+ return NS_ERROR;
+ }
+
+ return NSConsumerPushEvent(subscribeTask);
+}
+
+NSResult NSUnsubscribeProvider(NSProvider * provider)
+{
+ NSTask * unsubscribeTask = NSMakeTask(TASK_CONSUMER_REQ_SUBSCRIBE_CANCEL, (void *) provider);
+ if (!unsubscribeTask)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail");
+ return NS_ERROR;
+ }
+
+ return NSConsumerPushEvent(unsubscribeTask);
+}
+
+NSResult NSRescanProvider()
+{
+ NSTask * discoverTask = NSMakeTask(TASK_CONSUMER_REQ_DISCOVER, NULL);
+ if (!discoverTask)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail");
+ return NS_ERROR;
+ }
+
+ return NSConsumerPushEvent(discoverTask);
+}
+
+NSResult NSRead(NSMessage * obj)
+{
+ NSTask * readTask = NSMakeTask(TASK_SEND_READ, (void *) obj);
+ if (!readTask)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail");
+ return NS_ERROR;
+ }
+
+ return NSConsumerPushEvent(readTask);
+}
+
+NSResult NSDismiss(NSMessage * obj)
+{
+ NSTask * dismissTask = NSMakeTask(TASK_SEND_DISMISS, (void *) obj);
+ if (!dismissTask)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail");
+ return NS_ERROR;
+ }
+
+ return NSConsumerPushEvent(dismissTask);
+}
+
+NSResult NSDropNSObject(NSMessage * obj)
+{
+ if (!obj)
+ {
+ return NS_ERROR;
+ }
+
+ if (obj->mId)
+ {
+ OICFree(obj->mId);
+ obj->mId = NULL;
+ }
+
+ if (obj->mTitle)
+ {
+ OICFree(obj->mTitle);
+ obj->mTitle = NULL;
+ }
+
+ if (obj->mContentText)
+ {
+ OICFree(obj->mContentText);
+ obj->mContentText = NULL;
+ }
+
+ OICFree(obj);
+
+ return NS_OK;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerListener.h"
+
+#include <memory.h>
+#include <string.h>
+
+#include "NSConsumerCommon.h"
+#include "payload_logging.h"
+#include "cautilinterface.h"
+
+#include "NSConsumerDiscovery.h"
+
+#define NS_PRESENCE_SUBSCRIBE_QUERY "coap://224.0.1.187:5683/oic/ad?rt=oic.r.notification"
+
+typedef OCStackApplicationResult(*onRIResponse)(OCDoHandle, OCClientResponse *);
+
+OCStackApplicationResult NSRIResponseListener(
+ void * ctx, OCDoHandle handle, OCClientResponse * clientResponse);
+
+void NSConnectionStateListener(CATransportAdapter_t adapter,
+ const char *remote_address, bool connected);
+
+void NSAdapterStateListener(CATransportAdapter_t adapter, bool enabled);
+
+NSResult NSConsumerListenerInit()
+{
+ NSSetResponseListener(NSRIResponseListener);
+
+ // TODO replace with comment lines when enable network monitor of IP Adapter
+ CARegisterNetworkMonitorHandler(NSAdapterStateListener, NSConnectionStateListener);
+// if (CARegisterNetworkMonitorHandler(NSAdapterStateListener, NSConnectionStateListener)
+// != CA_STATUS_OK)
+// {
+// return NS_ERROR;
+// }
+
+ if (OC_STACK_OK != NSRequestToResourceIntrospection(NULL, OC_REST_PRESENCE, NULL,
+ NS_PRESENCE_SUBSCRIBE_QUERY, NULL, NSConsumerPresenceListener))
+ {
+ NS_CONSUMER_LOG(ERROR, "Presence request fail");
+ return NS_ERROR;
+ }
+
+ if (OC_STACK_OK != NSRequestToResourceIntrospection(NULL, OC_REST_DISCOVER, NULL,
+ NS_DISCOVER_QUERY, NULL, NSProviderDiscoverListener))
+ {
+ NS_CONSUMER_LOG(ERROR, "Discover request fail");
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+OCStackApplicationResult NSRIResponseListener(
+ void * ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+{
+ if (ctx == NULL)
+ {
+ NS_CONSUMER_LOG(ERROR, "Callback is null");
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ if (clientResponse->result == OC_STACK_OK && clientResponse != NULL)
+ {
+ OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
+ ((onRIResponse)ctx)(handle, clientResponse);
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+void NSConnectionStateListener(CATransportAdapter_t adapter,
+ const char *remote_address, bool connected)
+{
+ NS_CONSUMER_LOG_V(DEBUG, "adapter : %d", adapter);
+ NS_CONSUMER_LOG_V(DEBUG, "remote_address : %s", remote_address);
+ NS_CONSUMER_LOG_V(DEBUG, "isConnect : %d", connected);
+
+ (void) adapter;
+ (void) remote_address;
+
+ if (connected)
+ {
+ NS_CONSUMER_LOG(DEBUG, "try to discover notification provider.");
+
+ NSTask * task = NSMakeTask(TASK_EVENT_CONNECTED, NULL);
+ if (!task)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail.");
+ return;
+ }
+ NSConsumerPushEvent(task);
+ }
+}
+
+void NSAdapterStateListener(CATransportAdapter_t adapter, bool enabled)
+{
+ NS_CONSUMER_LOG_V(DEBUG, "adapter : %d", adapter);
+ NS_CONSUMER_LOG_V(DEBUG, "isEnabled : %d", enabled);
+
+ (void) adapter;
+
+ if (enabled)
+ {
+ NS_CONSUMER_LOG(DEBUG, "try to discover notification provider.");
+
+ NSTask * task = NSMakeTask(TASK_EVENT_CONNECTED, NULL);
+ if (!task)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail.");
+ return;
+ }
+ NSConsumerPushEvent(task);
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+// TODO move to other modules
+///////////////////////////////////////////////////////////////////////////////////////////////////
+//NSDiscoveredProvider * NSCreateDiscoveredProviderInfo(OCClientResponse *);
+//
+//OCStackResult NSSubscribeNotification(NSDiscoveredProvider * handle);
+//
+//NSObject * NSBuildOICNotification(OCClientResponse * clientResponse);
+//
+//
+//OCStackApplicationResult NSNotificationListener(
+// void * ctx, OCDoHandle handle, OCClientResponse * clientResponse)
+//{
+// if (!g_isStartedConsumer)
+// {
+// return OC_STACK_DELETE_TRANSACTION;
+// }
+//
+// (void) ctx;
+// (void) handle;
+// if (!clientResponse)
+// {
+// return OC_STACK_KEEP_TRANSACTION;
+// }
+//
+// if (clientResponse->result != OC_STACK_OK)
+// {
+// // TODO error handle.
+// return OC_STACK_KEEP_TRANSACTION;
+// }
+//
+// NSObject * notification = NSBuildOICNotification(clientResponse);
+// if (!notification)
+// {
+// // TODO error handle.
+// return OC_STACK_KEEP_TRANSACTION;
+// }
+//
+// g_NotificationPostedCB(notification);
+//
+// return OC_STACK_KEEP_TRANSACTION;
+//}
+//
+//OCStackResult NSSubscribeNotification(NSDiscoveredProvider * handle)
+//{
+// // TODO add provider list.
+//
+// OCDevAddr * addr = ((NSDiscoveredProvider *)handle)->addr;
+//
+// return NSRequestToResourceIntrospection(
+// ((NSDiscoveredProvider *)handle)->observeHandle,
+// OC_REST_OBSERVE, addr, NS_OBSERVE_QUERY,
+// NSNotificationListener, (void *)DEFAULT_CONTEXT_VALUE, NS_QOS);
+//}
+//
+//NSDiscoveredProvider * NSCreateDiscoveredProviderInfo(OCClientResponse * client)
+//{
+// NSDiscoveredProvider * discoveredProvider
+// = (NSDiscoveredProvider * )OICMalloc(sizeof(NSDiscoveredProvider));
+//
+// if (!discoveredProvider)
+// {
+// return NULL;
+// }
+//
+// discoveredProvider->addr = (OCDevAddr *)OICMalloc(sizeof(OCDevAddr));
+// memcpy(discoveredProvider->addr, client->addr,sizeof(OCDevAddr));
+//
+// return discoveredProvider;
+//}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_LISTENER_H_
+#define _NS_CONSUMER_LISTENER_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include "NSCommon.h"
+#include "ocstack.h"
+
+NSResult NSConsumerListenerInit();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_LISTENER_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerMessageHandler.h"
+
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include "oic_malloc.h"
+
+#include "NSStructs.h"
+#include "NSConsumerCommon.h"
+
+#include "NSThread.h"
+#include "NSConsumerQueue.h"
+
+#include "NSConsumerListener.h"
+#include "NSConsumerDiscovery.h"
+#include "NSConsumerSystem.h"
+#include "NSConsumerNotification.h"
+#include "NSConsumerSubsription.h"
+
+void * NSConsumerMsgHandleThreadFunc(void * handle);
+
+void * NSConsumerMsgPushThreadFunc(void * data);
+
+void NSConsumerHandleMsg(NSTask * task);
+
+NSThreadHandle ** NSGetMsgHandleThreadHandle()
+{
+ static NSThreadHandle * handle = NULL;
+ return & handle;
+}
+
+void NSSetMsgHandleThreadHandle(NSThreadHandle * handle)
+{
+ *(NSGetMsgHandleThreadHandle()) = handle;
+}
+
+NSConsumerQueue ** NSGetMsgHandleQueue()
+{
+ static NSConsumerQueue * queue = NULL;
+ return & queue;
+}
+
+void NSSetMsgHandleQueue(NSConsumerQueue * queue)
+{
+ *(NSGetMsgHandleQueue()) = queue;
+}
+
+NSResult NSConsumerMessageHandlerInit()
+{
+ NSThreadHandle * handle = NULL;
+ NSConsumerQueue * queue = NULL;
+
+ if (NS_OK != NSConsumerListenerInit())
+ {
+ NS_CONSUMER_LOG(ERROR, "listener init fail");
+ return NS_ERROR;
+ }
+
+ if (NS_OK != NSConsumerSystemInit())
+ {
+ NS_CONSUMER_LOG(ERROR, "system init fail");
+ return NS_ERROR;
+ }
+
+ handle = NSThreadInit(NSConsumerMsgHandleThreadFunc, NULL);
+ if (!handle)
+ {
+ NS_CONSUMER_LOG(ERROR, "msg handle thread init fail");
+ return NS_ERROR;
+ }
+ NSSetMsgHandleThreadHandle(handle);
+
+ queue = NSCreateQueue();
+ if (!queue)
+ {
+ NS_CONSUMER_LOG(ERROR, "msg handle queue create fail");
+ return NS_ERROR;
+ }
+ NSSetMsgHandleQueue(queue);
+
+ return NS_OK;
+}
+
+NSResult NSConsumerPushEvent(NSTask * task)
+{
+ if (!NSThreadInit(NSConsumerMsgPushThreadFunc, (void *) task))
+ {
+ NS_CONSUMER_LOG(ERROR, "insert to queue thread init fail");
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+void NSConsumerMessageHandlerExit()
+{
+ NSThreadStop(*(NSGetMsgHandleThreadHandle()));
+}
+
+void * NSConsumerMsgHandleThreadFunc(void * threadHandle)
+{
+ NSConsumerQueue * queue = NULL;
+ NSConsumerQueueObject * obj = NULL;
+ NSThreadHandle * handle = (NSThreadHandle *) threadHandle;
+ NS_CONSUMER_LOG(DEBUG, "created thread for consumer message handle");
+ if (!handle)
+ {
+ NS_CONSUMER_LOG(ERROR, "thread handle is null");
+ return NULL;
+ }
+
+ while (true)
+ {
+ if (!handle->isStarted)
+ {
+ NS_CONSUMER_LOG(ERROR, "msg handler thread will be terminated");
+ break;
+ }
+
+ queue = *(NSGetMsgHandleQueue());
+ if (!queue)
+ {
+ continue;
+ }
+
+ if (NSIsEmptyQueue(queue))
+ {
+ continue;
+ }
+
+ NSThreadLock(handle);
+ NS_CONSUMER_LOG(DEBUG, "msg handler working");
+ obj = NSPopQueue(queue);
+ // TODO processing obj
+
+ NSConsumerHandleMsg((NSTask *)(obj->data));
+
+ NSThreadUnlock(handle);
+
+ }
+
+ return NULL;
+}
+
+void * NSConsumerMsgPushThreadFunc(void * data)
+{
+ NSConsumerQueueObject * obj = NULL;
+ NSConsumerQueue * queue = NULL;
+ NSThreadHandle * handle = *(NSGetMsgHandleThreadHandle());
+ if (!handle)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSThreadHandle is null. can not insert to queue");
+ return NULL;
+ }
+
+ obj = (NSConsumerQueueObject *)OICMalloc(sizeof(NSConsumerQueueObject));
+ if (!obj)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSConsumerQueueObject allocation fail");
+ return NULL;
+ }
+
+ obj->data = data;
+ obj->next = NULL;
+
+ NSThreadLock(handle);
+
+ queue = *(NSGetMsgHandleQueue());
+ if (!queue)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSQueue is null. can not insert to queue");
+ OICFree(data);
+ OICFree(obj);
+ }
+ else
+ {
+ NSPushQueue(queue, obj);
+ }
+
+ NSThreadUnlock(handle);
+
+ return NULL;
+}
+
+void NSConsumerHandleMsg(NSTask * task)
+{
+ switch (task->taskType)
+ {
+ case TASK_EVENT_CONNECTED:
+ case TASK_CONSUMER_REQ_DISCOVER:
+ {
+ NSConsumerDiscoveryHandleMsg(task);
+ break;
+ }
+ case TASK_CONSUMER_REQ_SUBSCRIBE:
+ case TASK_SEND_READ:
+ case TASK_SEND_DISMISS:
+ {
+ NSConsumerNotificationHandleMsg(task);
+ break;
+ }
+ case TASK_RECV_READ:
+ case TASK_RECV_DISMISS:
+ case TASK_CONSUMER_RECV_NOTIFICATION:
+ {
+ NSConsumerSubscriptionHandleMsg(task);
+ break;
+ }
+ default:
+ NS_CONSUMER_LOG(ERROR, "Unknown type of task");
+ break;
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_MESSAGEHANDLER_H_
+#define _NS_CONSUMER_MESSAGEHANDLER_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdlib.h>
+#include <stdbool.h>
+
+#include "ocstack.h"
+#include "NSCommon.h"
+#include "NSStructs.h"
+
+NSResult NSConsumerMessageHandlerInit();
+
+void NSConsumerMessageHandlerExit();
+
+extern NSResult NSConsumerPushEvent(NSTask *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_MESSAGEHANDLER_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerNotification.h"
+
+#include "NSConsumerCommon.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "ocpayload.h"
+
+NSMessage_consumer * NSBuildOICNotification(OCClientResponse * clientResponse);
+NSSync * NSBuildOICNotificationSync(OCClientResponse * clientResponse);
+
+NSProvider * NSGetProvider(OCClientResponse * clientResponse);
+NSResult NSPushToCache(OCClientResponse * clientResponse, NSTaskType type);
+
+NSResult NSConsumerSubscribeProvider(NSProvider * provider)
+{
+ if (OC_STACK_OK != NSRequestToResourceIntrospection(NULL, OC_REST_OBSERVE,
+ (OCDevAddr *) provider->mUserData,
+ provider->messageUri, NULL, NSConsumerNotificationListener))
+ {
+ return NS_ERROR;
+ }
+
+ if (OC_STACK_OK != NSRequestToResourceIntrospection(NULL, OC_REST_OBSERVE,
+ (OCDevAddr *) provider->mUserData,
+ provider->syncUri, NULL, NSConsumerSyncListener))
+ {
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+NSResult NSConsumerPostProvider(OCDevAddr * addr, OCPayload * payload, const char * uri)
+{
+
+ if (OC_STACK_OK != NSRequestToResourceIntrospection(NULL, OC_REST_POST, addr,
+ uri, payload, NULL))
+ {
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+OCStackApplicationResult NSConsumerSyncListener(
+ OCDoHandle handle, OCClientResponse * clientResponse)
+{
+ (void) handle;
+
+ NSSync * newNoti = NULL;
+ NSProvider * provider = NSGetProvider(clientResponse);
+ if (!provider)
+ {
+ NS_CONSUMER_LOG(ERROR, "getting provider is failed");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ newNoti = NSBuildOICNotificationSync(clientResponse);
+ if (!newNoti)
+ {
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ NSTaskType taskType = TASK_RECV_READ;
+
+ if (newNoti->mState != Notification_Read)
+ {
+ NS_CONSUMER_LOG(DEBUG, "newNoti->type : Dismiss");
+ taskType = TASK_RECV_DISMISS;
+ }
+ else
+ {
+ NS_CONSUMER_LOG(DEBUG, "newNoti->type : Read");
+ }
+
+ NSNotificationSync(provider, newNoti);
+
+ if (NS_OK != NSPushToCache(clientResponse, taskType))
+ {
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+OCStackApplicationResult NSConsumerNotificationListener(
+ OCDoHandle handle, OCClientResponse * clientResponse)
+{
+ (void) handle;
+
+ NSProvider * provider = NSGetProvider(clientResponse);
+ if (!provider)
+ {
+ NS_CONSUMER_LOG(ERROR, "getting provider is failed");
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ NSMessage_consumer * newNoti = NSBuildOICNotification(clientResponse);
+ if (!newNoti)
+ {
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ NSTaskType taskType = TASK_CONSUMER_RECV_NOTIFICATION;
+
+ NS_CONSUMER_LOG(DEBUG, "newNoti->type == Notification");
+ NSNotificationPost(provider, (NSMessage *) newNoti);
+
+ if (NS_OK != NSPushToCache(clientResponse, taskType))
+ {
+ NSRemoveMessage(newNoti);
+ return OC_STACK_KEEP_TRANSACTION;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+}
+
+NSResult NSPushToCache(OCClientResponse * clientResponse, NSTaskType type)
+{
+ NSMessage_consumer * cachedNoti = NSBuildOICNotification(clientResponse);
+ if (!cachedNoti)
+ {
+ return NS_ERROR;
+ }
+ NSTask * task = NSMakeTask(type, (void *) cachedNoti);
+ if (!task)
+ {
+ NS_CONSUMER_LOG(ERROR, "NSTask allocation fail");
+ NSRemoveMessage(cachedNoti);
+ return NS_ERROR;
+ }
+ NSConsumerPushEvent(task);
+
+ return NS_OK;
+}
+
+NSMessage_consumer * NSBuildOICNotification(OCClientResponse * clientResponse)
+{
+ if(!clientResponse->payload)
+ {
+ return NULL;
+ }
+
+ NSMessage_consumer * retNoti = (NSMessage_consumer *)OICMalloc(sizeof(NSMessage_consumer));
+ if (!retNoti)
+ {
+ return NULL;
+ }
+
+ retNoti->mId = NULL;
+ retNoti->mTitle = NULL;
+ retNoti->mContentText = NULL;
+
+ OCRepPayload * payload = (OCRepPayload *)clientResponse->payload;
+ if (!OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_ID, &retNoti->mId))
+ {
+ NS_CONSUMER_LOG(ERROR, "id of received notification is null");
+ OICFree(retNoti);
+ return NULL;
+ }
+
+ OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_TITLE, &retNoti->mTitle);
+ OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_TEXT, &retNoti->mContentText);
+
+ NS_CONSUMER_LOG_V(DEBUG, "Msg ID : %s", retNoti->mId);
+ NS_CONSUMER_LOG_V(DEBUG, "Msg Title : %s", retNoti->mTitle);
+ NS_CONSUMER_LOG_V(DEBUG, "Msg Content : %s", retNoti->mContentText);
+
+ retNoti->addr = (OCDevAddr *)OICMalloc(sizeof(OCDevAddr));
+ memcpy(retNoti->addr, clientResponse->addr, sizeof(OCDevAddr));
+
+ retNoti->type = Notification;
+
+ return retNoti;
+}
+
+NSSync * NSBuildOICNotificationSync(OCClientResponse * clientResponse)
+{
+ if(!clientResponse->payload)
+ {
+ return NULL;
+ }
+ NSSync * retSync = (NSSync *)OICMalloc(sizeof(NSSync));
+ if (!retSync)
+ {
+ return NULL;
+ }
+
+ retSync->mMessageId = NULL;
+ retSync->mState = Notification_Read;
+
+ OCRepPayload * payload = (OCRepPayload *)clientResponse->payload;
+ if (!OCRepPayloadGetPropString(payload, NS_ATTRIBUTE_ID, &retSync->mMessageId))
+ {
+ NS_CONSUMER_LOG(ERROR, "id of received sync is null");
+ OICFree(retSync);
+ return NULL;
+ }
+ int64_t state;
+ if (!OCRepPayloadGetPropInt(payload, NS_ATTRIBUTE_STATE, & state))
+ {
+ NS_CONSUMER_LOG(ERROR, "state of received sync is null");
+ OICFree(retSync->mMessageId);
+ OICFree(retSync);
+ return NULL;
+ }
+
+ retSync->mState = (NSSyncTypes) state;
+
+ NS_CONSUMER_LOG_V(DEBUG, "Sync ID : %s", retSync->mMessageId);
+ NS_CONSUMER_LOG_V(DEBUG, "Sync State : %d", (int) retSync->mState);
+
+ return retSync;
+}
+
+NSProvider * NSGetProvider(OCClientResponse * clientResponse)
+{
+ NSProvider * newProvider = (NSProvider *)OICMalloc(sizeof(NSProvider));
+ if (!newProvider)
+ {
+ NS_CONSUMER_LOG(DEBUG, "NSProvider allocation fail");
+ return NULL;
+ }
+
+ // TODO set id
+ newProvider->mId = NULL;
+ newProvider->mUserData = (void *)OICMalloc(sizeof(OCDevAddr));
+ if (!newProvider->mUserData)
+ {
+ NS_CONSUMER_LOG(DEBUG, "OCDevAddr allocation fail");
+ OICFree(newProvider);
+ return NULL;
+ }
+ memcpy(newProvider->mUserData, clientResponse->addr, sizeof(OCDevAddr));
+
+ return newProvider;
+}
+
+void NSConsumerNotificationHandleMsg(NSTask * task)
+{
+ if (!task)
+ {
+ NS_CONSUMER_LOG(ERROR, "task is null");
+ return;
+ }
+
+ NS_CONSUMER_LOG_V(DEBUG, "Receive Event : %d", (int)task->taskType);
+ if (task->taskType == TASK_CONSUMER_REQ_SUBSCRIBE)
+ {
+ if (NS_OK != NSConsumerSubscribeProvider((NSProvider *)task->taskData))
+ {
+ NS_CONSUMER_LOG(ERROR, "Subscribe fail");
+ return;
+ }
+ }
+ else if (task->taskType == TASK_SEND_READ || task->taskType == TASK_SEND_DISMISS)
+ {
+ NSMessage_consumer * nsConsumer = (NSMessage_consumer *) task->taskData;
+ if (!nsConsumer)
+ {
+ NS_CONSUMER_LOG(ERROR, "taskData is NULL");
+ return;
+ }
+
+ OCRepPayload * payload = OCRepPayloadCreate ();
+ if (!payload)
+ {
+ NS_CONSUMER_LOG(ERROR, "Failed to create POST payload object");
+ return;
+ }
+ OCRepPayloadSetPropString(payload, "ID", (char *) nsConsumer->mId);
+ OCRepPayloadSetPropInt(payload, "STATE", (int) nsConsumer->type);
+
+ // TODO fix param for uri
+ if (NS_OK != NSConsumerPostProvider(
+ (OCDevAddr *) nsConsumer->addr, (OCPayload *) payload, "/notification/sync"))
+ {
+ NS_CONSUMER_LOG(ERROR, "Subscribe fail");
+ return;
+ }
+ }
+ else
+ {
+ NS_CONSUMER_LOG(ERROR, "Unknown type message");
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_NOTIFICATION_H_
+#define _NS_CONSUMER_NOTIFICATION_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdlib.h>
+
+#include "NSCommon.h"
+#include "NSStructs.h"
+#include "ocstack.h"
+
+void NSConsumerNotificationHandleMsg(NSTask *);
+
+NSResult NSConsumerSubscribeProvider(NSProvider *);
+NSResult NSConsumerPostProvider(OCDevAddr *, OCPayload *, const char *);
+
+OCStackApplicationResult NSConsumerNotificationListener(OCDoHandle, OCClientResponse *);
+
+OCStackApplicationResult NSConsumerSyncListener(OCDoHandle, OCClientResponse *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_NOTIFICATION_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerQueue.h"
+
+#include "oic_malloc.h"
+#include "NSConsumerCommon.h"
+
+NSConsumerQueue * NSCreateQueue()
+{
+ NSConsumerQueue * newQueue = (NSConsumerQueue *)OICMalloc(sizeof(NSConsumerQueue));
+ if (!newQueue)
+ {
+ return NULL;
+ }
+
+ newQueue->size = 0;
+ newQueue->head = NULL;
+ newQueue->tail = NULL;
+
+ return newQueue;
+}
+
+void NSDestroyQueue(NSConsumerQueue * queue)
+{
+ NSConsumerQueueObject * node = NSPopQueue(queue);
+ while(node)
+ {
+ node = (NSConsumerQueueObject *)node->next;
+ OICFree(node->data);
+ OICFree(node);
+ }
+
+ OICFree(queue);
+}
+
+bool NSPushQueue(NSConsumerQueue * queue, NSConsumerQueueObject * object)
+{
+ if (!queue)
+ {
+ return false;
+ }
+
+ if (!object)
+ {
+ NS_CONSUMER_LOG(ERROR, "object is null. can not insert to queue");
+ }
+
+ if (!(queue->head))
+ {
+ queue->head = object;
+ }
+ else
+ {
+ (queue->tail)->next = object;
+ }
+
+ queue->tail = object;
+ queue->size++;
+
+ return true;
+}
+
+NSConsumerQueueObject * NSPopQueue(NSConsumerQueue * queue)
+{
+ NSConsumerQueueObject * retObject = NULL;
+
+ if (!queue)
+ {
+ return NULL;
+ }
+
+ if (queue->size <= 0)
+ {
+ return NULL;
+ }
+
+ if (!(queue->head))
+ {
+ return NULL;
+ }
+
+ retObject = queue->head;
+
+ queue->head = (NSConsumerQueueObject *)(retObject->next);
+ if (!(queue->head))
+ {
+ queue->tail = NULL;
+ }
+ retObject->next = NULL;
+ queue->size--;
+
+ return retObject;
+}
+
+int NSGetQueueSize(NSConsumerQueue * queue)
+{
+ return queue->size;
+}
+
+bool NSIsEmptyQueue(NSConsumerQueue * queue)
+{
+ return (queue->size <= 0);
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_QUEUE_H_
+#define _NS_CONSUMER_QUEUE_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdbool.h>
+
+typedef struct _NSConsumerQueueObject
+{
+ void * data;
+ struct _NSConsumerQueueObject * next;
+} NSConsumerQueueObject;
+
+typedef struct
+{
+ int size;
+ NSConsumerQueueObject * head;
+ NSConsumerQueueObject * tail;
+} NSConsumerQueue;
+
+NSConsumerQueue * NSCreateQueue();
+
+void NSDestroyQueue(NSConsumerQueue *);
+
+bool NSPushQueue(NSConsumerQueue *, NSConsumerQueueObject *);
+
+NSConsumerQueueObject * NSPopQueue(NSConsumerQueue *);
+
+int NSGetQueueSize(NSConsumerQueue *);
+
+bool NSIsEmptyQueue(NSConsumerQueue *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_QUEUE_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerSubsription.h"
+
+#include "NSConsumerCommon.h"
+#include "NSConsumerCache.h"
+#include "NSStructs.h"
+
+#include "oic_malloc.h"
+
+NSCacheList ** NSGetCacheList()
+{
+ static NSCacheList * cache = NULL;
+ return & cache;
+}
+
+void NSSetCacheList(NSCacheList * cache)
+{
+ *(NSGetCacheList()) = cache;
+}
+
+NSResult NSCacheUpdate(NSCacheList * cache, NSTask * task, NSConsumerMessageTypes type)
+{
+ NSMessage_consumer * noti = (NSMessage_consumer *) task->taskData;
+ noti->type = type;
+
+ NSCacheObject * obj = (NSCacheObject *)OICMalloc(sizeof(NSCacheObject));
+ if (!obj)
+ {
+ NS_CONSUMER_LOG(ERROR, "Cache allocation is failed");
+ }
+ obj->data = (NSCacheData *) noti;
+ obj->next = NULL;
+
+ if (NS_OK != NSConsumerCacheWrite(cache, obj))
+ {
+ NS_CONSUMER_LOG(DEBUG, "CacheUpdate - NSConsumerCacheInsert");
+ if (NS_OK != NSConsumerCacheInsert(cache, (NSCacheObject *) obj))
+ {
+ NS_CONSUMER_LOG(ERROR, "Cache insert fail");
+ return NS_ERROR;
+ }
+ }
+
+ NSRemoveMessage(noti);
+ OICFree(obj);
+
+ return NS_OK;
+}
+
+void NSConsumerSubscriptionHandleMsg(NSTask * task)
+{
+ if (!task)
+ {
+ NS_CONSUMER_LOG(ERROR, "task is null");
+ return;
+ }
+
+ NSCacheList * cache;
+ if (!*(NSGetCacheList()))
+ {
+ NS_CONSUMER_LOG(DEBUG, "Cache Init");
+ cache = NSConsumerCacheInit();
+ if (!cache)
+ {
+ NS_CONSUMER_LOG(ERROR, "Cache create fail");
+ return;
+ }
+ NSSetCacheList(cache);
+ }
+ cache = *(NSGetCacheList());
+ if (!cache->head)
+ {
+ NS_CONSUMER_LOG(DEBUG, "Cache Head is null 2");
+ }
+ else{
+ NS_CONSUMER_LOG(DEBUG, "Cache Head is not null 2");
+ }
+
+
+ NS_CONSUMER_LOG_V(DEBUG, "Receive Event : %d", (int)task->taskType);
+
+ switch (task->taskType)
+ {
+ case TASK_CONSUMER_RECV_NOTIFICATION:
+ {
+ NS_CONSUMER_LOG(DEBUG, "Receive New Notification");
+
+ if (NS_OK != NSCacheUpdate(cache, task, Notification))
+ {
+ NS_CONSUMER_LOG(ERROR, "Cache Update fail");
+ return;
+ }
+ break;
+ }
+ case TASK_RECV_READ:
+ {
+ NS_CONSUMER_LOG(DEBUG, "Receive Read Notification");
+ // TODO update Cache.
+ if (NS_OK != NSCacheUpdate(cache, task, Read))
+ {
+ NS_CONSUMER_LOG(ERROR, "Cache Update fail");
+ return;
+ }
+ break;
+ }
+ case TASK_RECV_DISMISS:
+ {
+ NS_CONSUMER_LOG(DEBUG, "Receive Dismiss Notification");
+ if (NS_OK != NSCacheUpdate(cache, task, Dismiss))
+ {
+ NS_CONSUMER_LOG(ERROR, "Cache Update fail");
+ return;
+ }
+ break;
+ }
+ default :
+ {
+ NS_CONSUMER_LOG(ERROR, "Unknown TASK Type");
+ return ;
+ }
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_SUBSCRIPTION_H_
+#define _NS_CONSUMER_SUBSCRIPTION_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include "NSStructs.h"
+#include "NSConsumerCache.h"
+#include "NSConsumerNotification.h"
+
+void NSConsumerSubscriptionHandleMsg(NSTask *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_SUBSCRIPTION_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSConsumerSystem.h"
+#include "NSConsumerCommon.h"
+
+NSResult NSConsumerSystemInit()
+{
+ return NS_OK;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_CONSUMER_SYSTEM_H_
+#define _NS_CONSUMER_SYSTEM_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include "NSCommon.h"
+
+NSResult NSConsumerSystemInit();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_CONSUMER_SYSTEM_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSThread.h"
+
+#include "NSConsumerCommon.h"
+
+#include <memory.h>
+#include "oic_malloc.h"
+
+void NSDestroyThreadHandle(NSThreadHandle *);
+
+NSThreadHandle * NSThreadInit(NSThreadFunc func, void * data)
+{
+ if (!func)
+ {
+ NS_CONSUMER_LOG(ERROR, "thread function is null");
+ return NULL;
+ }
+
+ NSThreadHandle * handle = (NSThreadHandle *)OICMalloc(sizeof(NSThreadHandle));
+ if (!handle)
+ {
+ NS_CONSUMER_LOG(ERROR, "thread allocation fail");
+ return NULL;
+ }
+
+ memset(handle, 0, sizeof(NSThreadHandle));
+
+ pthread_mutexattr_init(&(handle->mutex_attr));
+ if (pthread_mutexattr_settype(&(handle->mutex_attr), PTHREAD_MUTEX_RECURSIVE))
+ {
+ NS_CONSUMER_LOG(ERROR, "thread mutex_attr init fail");
+ NSDestroyThreadHandle(handle);
+ return NULL;
+ }
+
+ if (pthread_mutex_init(&(handle->mutex), &(handle->mutex_attr)))
+ {
+ NS_CONSUMER_LOG(ERROR, "thread mutex init fail");
+ NSDestroyThreadHandle(handle);
+ return NULL;
+ }
+
+ if (pthread_mutex_lock(&(handle->mutex)))
+ {
+ NS_CONSUMER_LOG(ERROR, "thread mutex lock fail");
+ NSDestroyThreadHandle(handle);
+ return NULL;
+ }
+
+ handle->isStarted = true;
+
+ if (pthread_create(&(handle->thread_id), NULL, func,
+ (data == NULL) ? (void *) handle : (void *)data))
+ {
+ NS_CONSUMER_LOG(ERROR, "thread create fail");
+ NSDestroyThreadHandle(handle);
+ return NULL;
+ }
+
+ pthread_mutex_unlock(&(handle->mutex));
+
+ return handle;
+}
+
+void NSThreadLock(NSThreadHandle * handle)
+{
+ pthread_mutex_lock(&(handle->mutex));
+}
+
+void NSThreadUnlock(NSThreadHandle * handle)
+{
+ pthread_mutex_unlock(&(handle->mutex));
+}
+
+void NSThreadStop(NSThreadHandle * handle)
+{
+ NSDestroyThreadHandle(handle);
+}
+
+void NSDestroyThreadHandle(NSThreadHandle * handle)
+{
+ handle->isStarted = false;
+
+ if (handle->thread_id)
+ {
+ pthread_join(handle->thread_id, NULL);
+ }
+
+ pthread_mutex_destroy(&(handle->mutex));
+ pthread_mutexattr_destroy(&(handle->mutex_attr));
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_THREAD_H_
+#define _NS_THREAD_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include <stdbool.h>
+
+typedef enum
+{
+ pthread
+} NS_THREAD_MODEL;
+
+#define NS_THREAD pthread
+
+#if (NS_THREAD == pthread)
+#include <pthread.h>
+
+typedef struct
+{
+ bool isStarted;
+ pthread_t thread_id;
+ pthread_mutex_t mutex;
+ pthread_mutexattr_t mutex_attr;
+} NSThreadHandle;
+#endif
+
+typedef void *(*NSThreadFunc)(void *);
+
+NSThreadHandle * NSThreadInit(NSThreadFunc, void *);
+
+void NSThreadLock(NSThreadHandle *);
+
+void NSThreadUnlock(NSThreadHandle *);
+
+void NSThreadStop(NSThreadHandle *);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif // _NS_THREAD_H_
+++ /dev/null
-Initial commit for folder structure
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+#include "NSProviderCacheAdapter.h"\r
+\r
+\r
+NSWhiteList whiteMessageList;\r
+NSBlackList blackMessageList;\r
+\r
+NSWhiteList whiteSyncList;\r
+NSBlackList blackSyncList;\r
+\r
+NSResult NSProviderInitCache()\r
+{\r
+ // create cache\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSProviderWriteToCache(NSCache target, OCObservationId observeId, int state)\r
+{\r
+ printf("NSProviderWriteToCache - 0\n");\r
+ if(state == 0) // message\r
+ {\r
+ printf("NSProviderWriteToCache - 0 - 1\n");\r
+ if (NS_CONSUMER_BLACKLIST == target)\r
+ {\r
+ printf("NSProviderWriteToCache - 0 - 1 - 1\n");\r
+ blackMessageList.idList[blackMessageList.size] = observeId;\r
+ blackMessageList.size++;\r
+ }\r
+ else if (NS_CONSUMER_WHITELIST == target)\r
+ {\r
+ printf("NSProviderWriteToCache - 0 - 1 - 2\n");\r
+ whiteMessageList.idList[whiteMessageList.size] = observeId;\r
+ whiteMessageList.size++;\r
+ }\r
+ }\r
+ else if(state == 1)\r
+ {\r
+ printf("NSProviderWriteToCache - 1 - 1\n");\r
+ if (NS_CONSUMER_BLACKLIST == target)\r
+ {\r
+ printf("NSProviderWriteToCache - 1 - 1 - 1\n");\r
+ blackSyncList.idList[blackSyncList.size] = observeId;\r
+ blackSyncList.size++;\r
+ }\r
+ else if (NS_CONSUMER_WHITELIST == target)\r
+ {\r
+ printf("NSProviderWriteToCache - 1 - 1 - 2\n");\r
+ whiteSyncList.idList[whiteSyncList.size] = observeId;\r
+ whiteSyncList.size++;\r
+ }\r
+ }\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSCommonList * NSProviderReadCache(NSCache target, int state)\r
+{\r
+ if(state == 0) // message\r
+ {\r
+ if(NS_CONSUMER_BLACKLIST == target)\r
+ {\r
+ return (NSCommonList *)&blackMessageList;\r
+ }\r
+ else if(NS_CONSUMER_WHITELIST == target)\r
+ {\r
+ return (NSCommonList *)&whiteMessageList;\r
+ }\r
+ }\r
+ else if(state == 1)\r
+ {\r
+ if(NS_CONSUMER_BLACKLIST == target)\r
+ {\r
+ return (NSCommonList *)&blackSyncList;\r
+ }\r
+ else if(NS_CONSUMER_WHITELIST == target)\r
+ {\r
+ return (NSCommonList *)&whiteSyncList;\r
+ }\r
+ }\r
+ return NULL;\r
+}\r
+\r
+NSResult NSProviderDeleteCache()\r
+{\r
+ return NS_OK;\r
+}\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_CACHEADAPTER__H_\r
+#define _NS_PROVIDER_CACHEADAPTER__H_\r
+\r
+#include "logger.h"\r
+#include <octypes.h>\r
+#include "ocstack.h"\r
+#include "ocpayload.h"\r
+#include "NSStructs.h"\r
+#include "NSConstants.h"\r
+\r
+typedef struct _messageData\r
+{\r
+ NSMessage * msg;\r
+ uint8_t state;\r
+ uint8_t size;\r
+}NSMessageData;\r
+\r
+typedef struct _observerList\r
+{\r
+ OCObservationId idList[100];\r
+ uint8_t size;\r
+}NSWhiteList, NSBlackList;\r
+\r
+typedef NSWhiteList NSCommonList;\r
+\r
+NSResult NSProviderWriteToCache(NSCache target, OCObservationId observeId, int state);\r
+NSCommonList * NSProviderReadCache(NSCache target, int state);\r
+\r
+#endif /* _NS_PROVIDER_CACHE__H_ */\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include "NSProviderDiscovery.h"\r
+\r
+NSResult NSStartPresence()\r
+{\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "NSStartPresence()");\r
+\r
+ if (OCStartPresence(0) != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "NSStartPresence() NS_ERROR");\r
+ return NS_ERROR;\r
+ }\r
+\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "NSStartPresence() NS_OK");\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSStopPresence()\r
+{\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "NSStopPresence()");\r
+\r
+ if (OCStopPresence() != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "NSStopPresence() NS_ERROR");\r
+ return NS_ERROR;\r
+ }\r
+\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "NSStopPresence() NS_OK");\r
+ return NS_OK;\r
+}\r
+\r
+void * NSDiscoverySchedule(void * ptr)\r
+{\r
+ if (ptr == NULL)\r
+ {\r
+ OIC_LOG(INFO, DISCOVERY_TAG, "Create NSDiscoverySchedule");\r
+ }\r
+\r
+ while (NSIsRunning[DISCOVERY_SCHEDULER])\r
+ {\r
+ sem_wait(&NSSemaphore[DISCOVERY_SCHEDULER]);\r
+ pthread_mutex_lock(&NSMutex[DISCOVERY_SCHEDULER]);\r
+\r
+ if (NSHeadMsg[DISCOVERY_SCHEDULER] != NULL)\r
+ {\r
+ NSTask *node = NSHeadMsg[DISCOVERY_SCHEDULER];\r
+ NSHeadMsg[DISCOVERY_SCHEDULER] = node->nextTask;\r
+\r
+ switch (node->taskType)\r
+ {\r
+ case TASK_START_PRESENCE:\r
+ NSStartPresence();\r
+ break;\r
+ case TASK_STOP_PRESENCE:\r
+ NSStopPresence();\r
+ break;\r
+ case TASK_REGISTER_RESOURCE:\r
+ NSRegisterResource();\r
+ break;\r
+ }\r
+ OICFree(node);\r
+ }\r
+\r
+ pthread_mutex_unlock(&NSMutex[DISCOVERY_SCHEDULER]);\r
+\r
+ }\r
+ return NULL;\r
+}\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_DISCOVERY_H_\r
+#define _NS_PROVIDER_DISCOVERY_H_\r
+\r
+#include "NSCommon.h"\r
+#include "NSStructs.h"\r
+#include "NSQueueScheduler.h"\r
+#include "NSProviderResource.h"\r
+\r
+NSResult NSStartPresence();\r
+NSResult NSStopPresence();\r
+\r
+#endif /* _NS_PROVIDER_DISCOVERY_H_ */\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include "NSProviderInterface.h"\r
+#include "NSQueueScheduler.h"\r
+#include "NSProviderListener.h"\r
+#include "cautilinterface.h"\r
+\r
+bool initSchedule = false;\r
+static NSSubscribeRequestCallback g_subscribeRequestCb = NULL;\r
+static NSSyncCallback g_syncCb = NULL;\r
+\r
+void NSRegisterSubscribeRequestCb(NSSubscribeRequestCallback subscribeRequestCb)\r
+{\r
+ g_subscribeRequestCb = subscribeRequestCb;\r
+}\r
+\r
+void NSRegisterSyncCb(NSSyncCallback syncCb)\r
+{\r
+ g_syncCb = syncCb;\r
+}\r
+\r
+void NSSubscribeRequestCb(NSConsumer *consumer)\r
+{\r
+ g_subscribeRequestCb(consumer);\r
+}\r
+\r
+void NSSyncCb(NSProvider *provider, NSSync *sync)\r
+{\r
+ g_syncCb(provider, sync);\r
+}\r
+\r
+NSResult NSStartProvider(NSAccessPolicy policy, NSSubscribeRequestCallback subscribeRequestCb,\r
+ NSSyncCallback syncCb)\r
+{\r
+ OIC_LOG(INFO, INTERFACE_TAG, "Notification Service Start Provider..");\r
+\r
+ NSSetSubscriptionAcceptPolicy(policy);\r
+\r
+ if (!initSchedule)\r
+ {\r
+ initSchedule = true;\r
+ NSInitScheduler();\r
+ NSStartScheduler();\r
+ }\r
+\r
+ NSRegisterSubscribeRequestCb(subscribeRequestCb);\r
+ NSRegisterSyncCb(syncCb);\r
+\r
+ CARegisterNetworkMonitorHandler(NSProviderAdapterStateListener,\r
+ NSProviderConnectionStateListener);\r
+\r
+ NSPushQueue(DISCOVERY_SCHEDULER, TASK_START_PRESENCE, NULL);\r
+ NSPushQueue(DISCOVERY_SCHEDULER, TASK_REGISTER_RESOURCE, NULL);\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSStopProvider()\r
+{\r
+ NSRegisterSubscribeRequestCb(NULL);\r
+ NSRegisterSyncCb(NULL);\r
+ initSchedule = false;\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSSendNotification(NSMessage *msg)\r
+{\r
+ OIC_LOG(INFO, INTERFACE_TAG, "Send Notification");\r
+\r
+ NSPushQueue(NOTIFICATION_SCHEDULER, TASK_SEND_NOTIFICATION, msg);\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSReadCheck(NSMessage *msg)\r
+{\r
+ OIC_LOG(INFO, INTERFACE_TAG, "Read Sync");\r
+\r
+ NSTask * task = (NSTask*) OICMalloc(sizeof(NSTask));\r
+ if (!task)\r
+ {\r
+ OIC_LOG(ERROR, LISTENER_TAG, PCF("Fail to allocate memory"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ task->nextTask = NULL;\r
+ task->taskData = msg;\r
+ task->taskType = TASK_SEND_READ;\r
+\r
+ NSPushQueue(NOTIFICATION_SCHEDULER, task->taskType, task);\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSAccept(NSConsumer *consumer, bool accepted)\r
+{\r
+ OIC_LOG(INFO, INTERFACE_TAG, "Response Acceptance");\r
+\r
+ NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SEND_ALLOW, consumer);\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSGetConsumerList(uint8_t *list, uint32_t size)\r
+{\r
+ OIC_LOG(INFO, INTERFACE_TAG, "Get consumer list");\r
+\r
+ NSGetObsIdList(list);\r
+ size = NSGetNumberOfObsList();\r
+\r
+ return NS_OK;\r
+}\r
+\r
+void * NSResponseSchedule(void * ptr)\r
+{\r
+ if (ptr == NULL)\r
+ {\r
+ OIC_LOG(ERROR, INTERFACE_TAG, "Fail to response to User");\r
+ }\r
+\r
+ while (NSIsRunning[RESPONSE_SCHEDULER])\r
+ {\r
+ sem_wait(&NSSemaphore[RESPONSE_SCHEDULER]);\r
+ pthread_mutex_lock(&NSMutex[RESPONSE_SCHEDULER]);\r
+\r
+ if (NSHeadMsg[RESPONSE_SCHEDULER] != NULL)\r
+ {\r
+ NSTask *node = NSHeadMsg[RESPONSE_SCHEDULER];\r
+ NSHeadMsg[RESPONSE_SCHEDULER] = node->nextTask;\r
+\r
+ switch (node->taskType)\r
+ {\r
+ case TASK_CB_SUBSCRIPTION:\r
+ {\r
+ printf("before - TASK_CB_SUBSCRIPTION :\n");\r
+ OCEntityHandlerRequest * request = (OCEntityHandlerRequest*)node->taskData;\r
+ NSConsumer consumer;\r
+ consumer.mId = strdup(request->devAddr.addr);\r
+ int * obId = (int *) malloc (sizeof(int));\r
+ *obId = request->obsInfo.obsId;\r
+ consumer.mUserData = obId;\r
+\r
+ NSSubscribeRequestCb(&consumer);\r
+ printf("after - TASK_CB_SUBSCRIPTION :\n");\r
+ break;\r
+ }\r
+ case TASK_CB_SYNC:\r
+ {\r
+ NSSync * sync = (NSSync*)node->taskData;\r
+ NSSyncCb(NULL, sync);\r
+ break;\r
+ }\r
+ default:\r
+ OIC_LOG(INFO, INTERFACE_TAG, "Response to User");\r
+\r
+ // TODO: NSSubscribeRequestCb\r
+\r
+ // TODO: NSSyncCb\r
+\r
+ break;\r
+\r
+ }\r
+ OICFree(node);\r
+ }\r
+\r
+ pthread_mutex_unlock(&NSMutex[RESPONSE_SCHEDULER]);\r
+\r
+ }\r
+ return NULL;\r
+}\r
+\r
+NSResult NSTestStartPresence()\r
+{\r
+ NSPushQueue(DISCOVERY_SCHEDULER, TASK_START_PRESENCE, NULL);\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSTestStopPresence()\r
+{\r
+ NSPushQueue(DISCOVERY_SCHEDULER, TASK_STOP_PRESENCE, NULL);\r
+ return NS_OK;\r
+}\r
+\r
+\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include "NSProviderListener.h"\r
+\r
+OCEntityHandlerResult NSEntityHandlerNotificationCb(OCEntityHandlerFlag flag,\r
+ OCEntityHandlerRequest *entityHandlerRequest, void* callback)\r
+{\r
+ OIC_LOG_V (INFO, LISTENER_TAG, "Inside entity handler - flags: 0x%x", flag);\r
+\r
+ OCEntityHandlerResult ehResult = OC_EH_OK;\r
+ OCEntityHandlerResponse response =\r
+ { 0, 0, OC_EH_ERROR, 0, 0,\r
+ { },\r
+ { 0 }, false };\r
+\r
+ // Validate pointer\r
+ if (!entityHandlerRequest)\r
+ {\r
+ OIC_LOG (ERROR, LISTENER_TAG, "Invalid request pointer");\r
+ return OC_EH_ERROR;\r
+ }\r
+\r
+ // Initialize certain response fields\r
+ response.numSendVendorSpecificHeaderOptions = 0;\r
+ memset(response.sendVendorSpecificHeaderOptions, 0,\r
+ sizeof response.sendVendorSpecificHeaderOptions);\r
+ memset(response.resourceUri, 0, sizeof response.resourceUri);\r
+ OCRepPayload* payload = NULL;\r
+\r
+ if (flag & OC_REQUEST_FLAG)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Flag includes OC_REQUEST_FLAG");\r
+\r
+ if (OC_REST_GET == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_GET from client");\r
+\r
+ NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SEND_POLICY, entityHandlerRequest);\r
+ ehResult = OC_EH_OK;\r
+\r
+ }\r
+ else if (OC_REST_PUT == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_PUT from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_POST == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_POST from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_DELETE == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_DELETE from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else\r
+ {\r
+ OIC_LOG_V (INFO, LISTENER_TAG, "Received unsupported method %d from client",\r
+ entityHandlerRequest->method);\r
+ ehResult = OC_EH_OK;\r
+ }\r
+\r
+ // If the result isn't an error or forbidden, send response\r
+ if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))\r
+ {\r
+ // Format the response. Note this requires some info about the request\r
+ response.requestHandle = entityHandlerRequest->requestHandle;\r
+ response.resourceHandle = entityHandlerRequest->resource;\r
+ response.ehResult = ehResult;\r
+ //response.payload = reinterpret_cast<OCPayload*>(payload);\r
+ response.payload = (OCPayload*) payload;\r
+ // Indicate that response is NOT in a persistent buffer\r
+ response.persistentBufferFlag = 0;\r
+\r
+ // Handle vendor specific options\r
+ if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions\r
+ && entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received vendor specific options");\r
+ uint8_t i = 0;\r
+ OCHeaderOption * rcvdOptions = entityHandlerRequest->rcvdVendorSpecificHeaderOptions;\r
+ for (i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)\r
+ {\r
+ if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)\r
+ {\r
+ OIC_LOG_V(INFO, LISTENER_TAG, "Received option with OC_COAP_ID and ID %u with",\r
+ ((OCHeaderOption)rcvdOptions[i]).optionID );\r
+\r
+ OIC_LOG_BUFFER(INFO, LISTENER_TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,\r
+ MAX_HEADER_OPTION_DATA_LENGTH);\r
+ }\r
+ }\r
+ OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;\r
+ uint8_t option2[] =\r
+ { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 };\r
+ uint8_t option3[] =\r
+ { 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 };\r
+ sendOptions[0].protocolID = OC_COAP_ID;\r
+ sendOptions[0].optionID = 2248;\r
+ memcpy(sendOptions[0].optionData, option2, sizeof(option2));\r
+ sendOptions[0].optionLength = 10;\r
+ sendOptions[1].protocolID = OC_COAP_ID;\r
+ sendOptions[1].optionID = 2600;\r
+ memcpy(sendOptions[1].optionData, option3, sizeof(option3));\r
+ sendOptions[1].optionLength = 10;\r
+ response.numSendVendorSpecificHeaderOptions = 2;\r
+ }\r
+\r
+\r
+ // Send the response\r
+ /*if (OCDoResponse(&response) != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(ERROR, LISTENER_TAG, "Error sending response");\r
+ ehResult = OC_EH_ERROR;\r
+ }*/\r
+ }\r
+ }\r
+\r
+ OCPayloadDestroy(response.payload);\r
+ return ehResult;\r
+}\r
+\r
+OCEntityHandlerResult NSEntityHandlerMessageCb(OCEntityHandlerFlag flag,\r
+ OCEntityHandlerRequest *entityHandlerRequest, void* callback)\r
+{\r
+ OIC_LOG_V (INFO, LISTENER_TAG, "Inside entity handler - flags: 0x%x", flag);\r
+\r
+ OCEntityHandlerResult ehResult = OC_EH_OK;\r
+ OCEntityHandlerResponse response =\r
+ { 0, 0, OC_EH_ERROR, 0, 0,\r
+ { },\r
+ { 0 }, false };\r
+\r
+ // Validate pointer\r
+ if (!entityHandlerRequest)\r
+ {\r
+ OIC_LOG (ERROR, LISTENER_TAG, "Invalid request pointer");\r
+ return OC_EH_ERROR;\r
+ }\r
+\r
+ // Initialize certain response fields\r
+ response.numSendVendorSpecificHeaderOptions = 0;\r
+ memset(response.sendVendorSpecificHeaderOptions, 0,\r
+ sizeof response.sendVendorSpecificHeaderOptions);\r
+ memset(response.resourceUri, 0, sizeof response.resourceUri);\r
+ OCRepPayload* payload = NULL;\r
+\r
+ if (flag & OC_REQUEST_FLAG)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Flag includes OC_REQUEST_FLAG");\r
+\r
+ if (OC_REST_GET == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_GET from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_PUT == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_PUT from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_POST == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_POST from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_DELETE == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_DELETE from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else\r
+ {\r
+ OIC_LOG_V (INFO, LISTENER_TAG, "Received unsupported method %d from client",\r
+ entityHandlerRequest->method);\r
+ ehResult = OC_EH_OK;\r
+ }\r
+\r
+ // If the result isn't an error or forbidden, send response\r
+ if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))\r
+ {\r
+ // Format the response. Note this requires some info about the request\r
+ response.requestHandle = entityHandlerRequest->requestHandle;\r
+ response.resourceHandle = entityHandlerRequest->resource;\r
+ response.ehResult = ehResult;\r
+ //response.payload = reinterpret_cast<OCPayload*>(payload);\r
+ response.payload = (OCPayload*) payload;\r
+ // Indicate that response is NOT in a persistent buffer\r
+ response.persistentBufferFlag = 0;\r
+\r
+ // Handle vendor specific options\r
+ if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions\r
+ && entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received vendor specific options");\r
+ uint8_t i = 0;\r
+ OCHeaderOption * rcvdOptions = entityHandlerRequest->rcvdVendorSpecificHeaderOptions;\r
+ for (i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)\r
+ {\r
+ if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)\r
+ {\r
+ OIC_LOG_V(INFO, LISTENER_TAG, "Received option with OC_COAP_ID and ID %u with",\r
+ ((OCHeaderOption)rcvdOptions[i]).optionID );\r
+\r
+ OIC_LOG_BUFFER(INFO, LISTENER_TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,\r
+ MAX_HEADER_OPTION_DATA_LENGTH);\r
+ }\r
+ }\r
+ OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;\r
+ uint8_t option2[] =\r
+ { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 };\r
+ uint8_t option3[] =\r
+ { 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 };\r
+ sendOptions[0].protocolID = OC_COAP_ID;\r
+ sendOptions[0].optionID = 2248;\r
+ memcpy(sendOptions[0].optionData, option2, sizeof(option2));\r
+ sendOptions[0].optionLength = 10;\r
+ sendOptions[1].protocolID = OC_COAP_ID;\r
+ sendOptions[1].optionID = 2600;\r
+ memcpy(sendOptions[1].optionData, option3, sizeof(option3));\r
+ sendOptions[1].optionLength = 10;\r
+ response.numSendVendorSpecificHeaderOptions = 2;\r
+ }\r
+ }\r
+ }\r
+\r
+ if (flag & OC_OBSERVE_FLAG)\r
+ {\r
+ OIC_LOG(INFO, LISTENER_TAG, "Flag includes OC_OBSERVE_FLAG");\r
+\r
+ if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_OBSERVE_REGISTER from client");\r
+\r
+ printf("NS_ register message observerID : %d\n", entityHandlerRequest->obsInfo.obsId);\r
+ NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_RECV_SUBSCRIPTION, entityHandlerRequest);\r
+\r
+ }\r
+ }\r
+\r
+ OCPayloadDestroy(response.payload);\r
+ return ehResult;\r
+}\r
+\r
+OCEntityHandlerResult NSEntityHandlerSyncCb(OCEntityHandlerFlag flag,\r
+ OCEntityHandlerRequest *entityHandlerRequest, void* callback)\r
+{\r
+ OIC_LOG_V (INFO, LISTENER_TAG, "Inside entity handler - flags: 0x%x", flag);\r
+\r
+ OCEntityHandlerResult ehResult = OC_EH_OK;\r
+ OCEntityHandlerResponse response =\r
+ { 0, 0, OC_EH_ERROR, 0, 0,\r
+ { },\r
+ { 0 }, false };\r
+\r
+ // Validate pointer\r
+ if (!entityHandlerRequest)\r
+ {\r
+ OIC_LOG (ERROR, LISTENER_TAG, "Invalid request pointer");\r
+ return OC_EH_ERROR;\r
+ }\r
+\r
+ // Initialize certain response fields\r
+ response.numSendVendorSpecificHeaderOptions = 0;\r
+ memset(response.sendVendorSpecificHeaderOptions, 0,\r
+ sizeof response.sendVendorSpecificHeaderOptions);\r
+ memset(response.resourceUri, 0, sizeof response.resourceUri);\r
+ OCRepPayload* payload = NULL;\r
+\r
+ if (flag & OC_REQUEST_FLAG)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Flag includes OC_REQUEST_FLAG");\r
+\r
+ if (OC_REST_GET == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_GET from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_PUT == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_PUT from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_POST == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_POST from client");\r
+\r
+ NSPushQueue(NOTIFICATION_SCHEDULER, TASK_SEND_READ, NSBuildOICNotificationSync(entityHandlerRequest->payload));\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else if (OC_REST_DELETE == entityHandlerRequest->method)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_REST_DELETE from client");\r
+ ehResult = OC_EH_OK;\r
+ }\r
+ else\r
+ {\r
+ OIC_LOG_V (INFO, LISTENER_TAG, "Received unsupported method %d from client",\r
+ entityHandlerRequest->method);\r
+ ehResult = OC_EH_OK;\r
+ }\r
+\r
+ // If the result isn't an error or forbidden, send response\r
+ if (!((ehResult == OC_EH_ERROR) || (ehResult == OC_EH_FORBIDDEN)))\r
+ {\r
+ // Format the response. Note this requires some info about the request\r
+ response.requestHandle = entityHandlerRequest->requestHandle;\r
+ response.resourceHandle = entityHandlerRequest->resource;\r
+ response.ehResult = ehResult;\r
+ //response.payload = reinterpret_cast<OCPayload*>(payload);\r
+ response.payload = (OCPayload*) payload;\r
+ // Indicate that response is NOT in a persistent buffer\r
+ response.persistentBufferFlag = 0;\r
+\r
+ // Handle vendor specific options\r
+ if (entityHandlerRequest->rcvdVendorSpecificHeaderOptions\r
+ && entityHandlerRequest->numRcvdVendorSpecificHeaderOptions)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received vendor specific options");\r
+ uint8_t i = 0;\r
+ OCHeaderOption * rcvdOptions = entityHandlerRequest->rcvdVendorSpecificHeaderOptions;\r
+ for (i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++)\r
+ {\r
+ if (((OCHeaderOption) rcvdOptions[i]).protocolID == OC_COAP_ID)\r
+ {\r
+ OIC_LOG_V(INFO, LISTENER_TAG, "Received option with OC_COAP_ID and ID %u with",\r
+ ((OCHeaderOption)rcvdOptions[i]).optionID );\r
+\r
+ OIC_LOG_BUFFER(INFO, LISTENER_TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,\r
+ MAX_HEADER_OPTION_DATA_LENGTH);\r
+ }\r
+ }\r
+ OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions;\r
+ uint8_t option2[] =\r
+ { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 };\r
+ uint8_t option3[] =\r
+ { 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 };\r
+ sendOptions[0].protocolID = OC_COAP_ID;\r
+ sendOptions[0].optionID = 2248;\r
+ memcpy(sendOptions[0].optionData, option2, sizeof(option2));\r
+ sendOptions[0].optionLength = 10;\r
+ sendOptions[1].protocolID = OC_COAP_ID;\r
+ sendOptions[1].optionID = 2600;\r
+ memcpy(sendOptions[1].optionData, option3, sizeof(option3));\r
+ sendOptions[1].optionLength = 10;\r
+ response.numSendVendorSpecificHeaderOptions = 2;\r
+ }\r
+ }\r
+ }\r
+\r
+ if (flag & OC_OBSERVE_FLAG)\r
+ {\r
+ OIC_LOG(INFO, LISTENER_TAG, "Flag includes OC_OBSERVE_FLAG");\r
+\r
+ if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "Received OC_OBSERVE_REGISTER from client");\r
+ printf("NS_ register sync observerID : %d\n", entityHandlerRequest->obsInfo.obsId);\r
+ NSPushQueue(SUBSCRIPTION_SCHEDULER, TASK_SYNC_SUBSCRIPTION, entityHandlerRequest);\r
+ }\r
+ }\r
+\r
+\r
+ OCPayloadDestroy(response.payload);\r
+ return ehResult;\r
+}\r
+\r
+void NSProviderConnectionStateListener(CATransportAdapter_t adapter, const char *remote_address,\r
+ bool connected)\r
+{\r
+ OIC_LOG (INFO, LISTENER_TAG, "Connection State Changed");\r
+\r
+ if (connected)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "CONNECTED");\r
+\r
+ // Set Connection State\r
+ NSSetProviderConnectionState(CONNECTED);\r
+\r
+ // Start Presence\r
+ NSPushQueue(DISCOVERY_SCHEDULER, TASK_START_PRESENCE, NULL);\r
+ }\r
+}\r
+\r
+void NSProviderAdapterStateListener(CATransportAdapter_t adapter, bool enabled)\r
+{\r
+ OIC_LOG (INFO, LISTENER_TAG, "Adapter State Changed");\r
+\r
+ if (enabled)\r
+ {\r
+ OIC_LOG (INFO, LISTENER_TAG, "CONNECTED");\r
+\r
+ // Set Connection State\r
+ NSSetProviderConnectionState(CONNECTED);\r
+\r
+ // Start Presence\r
+ NSPushQueue(DISCOVERY_SCHEDULER, TASK_START_PRESENCE, NULL);\r
+ }\r
+}\r
+\r
+NSSync * NSBuildOICNotificationSync(OCPayload * payload)\r
+{\r
+ if(!payload)\r
+ {\r
+ return NULL;\r
+ }\r
+ NSSync * retSync = (NSSync *)OICMalloc(sizeof(NSSync));\r
+ if (!retSync)\r
+ {\r
+ return NULL;\r
+ }\r
+\r
+ retSync->mMessageId = NULL;\r
+ retSync->mState = Notification_Read;\r
+\r
+ OCRepPayload * repPayload = (OCRepPayload *)payload;\r
+ if (!OCRepPayloadGetPropString(repPayload, NS_ATTRIBUTE_ID, &retSync->mMessageId))\r
+ {\r
+ OIC_LOG(DEBUG, LISTENER_TAG, "id of received sync is null");\r
+ OICFree(retSync);\r
+ return NULL;\r
+ }\r
+ int64_t state;\r
+ if (!OCRepPayloadGetPropInt(repPayload, NS_ATTRIBUTE_STATE, & state))\r
+ {\r
+\r
+ OIC_LOG(DEBUG, LISTENER_TAG, "id of received sync is null");\r
+\r
+ OICFree(retSync->mMessageId);\r
+ OICFree(retSync);\r
+ return NULL;\r
+ }\r
+\r
+ retSync->mState = (NSSyncTypes) state;\r
+\r
+ OIC_LOG_V(DEBUG, LISTENER_TAG, "Sync ID : %s", retSync->mMessageId);\r
+ OIC_LOG_V(DEBUG, LISTENER_TAG, "Sync State : %d", (int) retSync->mState);\r
+\r
+ return retSync;\r
+}\r
+\r
+NSResult NSMakeTask(NSTaskType type, OCEntityHandlerRequest *request, NSTask * task)\r
+{\r
+ task = (NSTask*) OICMalloc(sizeof(NSTask));\r
+ if (!task)\r
+ {\r
+ OIC_LOG(ERROR, LISTENER_TAG, PCF("Fail to allocate memory"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ task->taskType = type;\r
+ task->taskData = request;\r
+ task->nextTask = NULL;\r
+\r
+ return NS_OK;\r
+}\r
+\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_LISTENER__H_\r
+#define _NS_PROVIDER_LISTENER__H_\r
+\r
+#include <octypes.h>\r
+#include "ocstack.h"\r
+#include "logger.h"\r
+#include "ocpayload.h"\r
+#include "NSStructs.h"\r
+#include "NSConstants.h"\r
+#include "NSProviderSystem.h"\r
+#include "cautilinterface.h"\r
+\r
+OCEntityHandlerResult NSEntityHandlerNotificationCb(OCEntityHandlerFlag flag,\r
+ OCEntityHandlerRequest *entityHandlerRequest, void* callback);\r
+\r
+OCEntityHandlerResult NSEntityHandlerMessageCb(OCEntityHandlerFlag flag,\r
+ OCEntityHandlerRequest *entityHandlerRequest, void* callback);\r
+\r
+OCEntityHandlerResult NSEntityHandlerSyncCb(OCEntityHandlerFlag flag,\r
+ OCEntityHandlerRequest *entityHandlerRequest, void* callback);\r
+\r
+void NSProviderConnectionStateListener(CATransportAdapter_t adapter, const char *remote_address,\r
+ bool connected);\r
+\r
+void NSProviderAdapterStateListener(CATransportAdapter_t adapter, bool enabled);\r
+\r
+NSResult NSMakeTask(NSTaskType type, OCEntityHandlerRequest *request, NSTask * task);\r
+\r
+NSSync * NSBuildOICNotificationSync(OCPayload * payload);\r
+\r
+#endif /* _NS_PROVIDER_LISTENER__H_ */\r
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSProviderNotification.h"
+
+NSResult NSGetObsIdList(OCObservationId *list)
+{
+ // // TODO: return white list
+
+ list = NULL;
+
+ return NS_OK;
+}
+
+uint32_t NSGetNumberOfObsList()
+{
+ // TODO: return # of list
+
+ return 0;
+}
+
+NSResult NSGetMessagePayload(NSMessage *msg, OCRepPayload** msgPayload)
+{
+
+ *msgPayload = OCRepPayloadCreate();
+
+ if (!*msgPayload)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Failed to allocate payload"));
+ return NS_ERROR;
+ }
+
+ OCRepPayloadSetUri(*msgPayload, NSGetNotificationMessageUri());
+ OCRepPayloadSetPropString(*msgPayload, NS_ATTRIBUTE_ID, msg->mId);
+ OCRepPayloadSetPropString(*msgPayload, NS_ATTRIBUTE_TITLE, msg->mTitle);
+ OCRepPayloadSetPropString(*msgPayload, NS_ATTRIBUTE_TEXT, msg->mContentText);
+
+ return NS_OK;
+}
+
+NSResult NSGetSyncPayload(NSSync *sync, OCRepPayload** syncPayload)
+{
+
+ *syncPayload = OCRepPayloadCreate();
+
+ if (!*syncPayload)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Failed to allocate payload"));
+ return NS_ERROR;
+ }
+
+ OCRepPayloadSetUri(*syncPayload, NSGetNotificationSyncUri());
+ OCRepPayloadSetPropString(*syncPayload, NS_ATTRIBUTE_ID, sync->mMessageId);
+ OCRepPayloadSetPropInt(*syncPayload, NS_ATTRIBUTE_STATE, sync->mState);
+
+ return NS_OK;
+}
+
+NSResult NSSendMessage(NSMessage *msg)
+{
+ OIC_LOG(DEBUG, NOTIFICATION_TAG, "Send Notification Message to consumer");
+ int i;
+ // Set Resource and get resource handle
+ OCResourceHandle rHandle;
+ if (NSPutMessageResource(msg, &rHandle) != NS_OK)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Fail to put notification resource"));
+ return NS_ERROR;
+ }
+
+ // Send Notification to subscribers
+
+ NSWhiteList * whiteList = NSProviderReadCache(NS_CONSUMER_WHITELIST, 0);
+
+ if(whiteList->size == 0)
+ {
+ printf("printf - no observers\n");
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("no observers"));
+ return NS_ERROR;
+ }
+
+ OCRepPayload* payload;
+ printf("printf - no observers - 1\n");
+ if (NSGetMessagePayload(msg, &payload) != NS_OK)
+ {
+ printf("printf - no observers - 2\n");
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Failed to allocate payload"));
+ return NS_ERROR;
+ }
+
+ for(i = 0; i < whiteList->size; ++i)
+ {
+ printf("NS_ -------------------------------------------------------message\n");
+ printf("NS_ whiteList->idList[%d] = %d\n", i, whiteList->idList[i]);
+ printf("NS_ -------------------------------------------------------message\n");
+ }
+
+ // Notify message to subscribers
+
+ OCStackResult ocstackResult = OCNotifyListOfObservers(rHandle, whiteList->idList, whiteList->size, payload, OC_LOW_QOS);
+ printf("NS_ message ocstackResult = %d\n", ocstackResult);
+
+
+ if (ocstackResult != OC_STACK_OK)
+ {
+ printf("printf - no observers - 3\n");
+ OIC_LOG(ERROR, NOTIFICATION_TAG, "fail to send message");
+ OCRepPayloadDestroy(payload);
+ return NS_ERROR;
+
+ }
+ printf("printf - no observers - 4\n");
+ OCRepPayloadDestroy(payload);
+
+ return NS_OK;
+}
+
+NSResult NSSendSync(NSSync *sync)
+{
+ OIC_LOG(DEBUG, NOTIFICATION_TAG, "Send Notification Sync to consumer");
+ int i;
+ // Set Resource and get resource handle
+
+ OCResourceHandle rHandle;
+ if (NSPutSyncResource(sync, &rHandle) != NS_OK)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Fail to put sync resource"));
+ return NS_ERROR;
+ }
+
+ NSWhiteList * whiteList = NSProviderReadCache(NS_CONSUMER_WHITELIST, 1);
+
+ if(whiteList->size == 0)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("no observers"));
+ return NS_ERROR;
+ }
+
+ // Send sync to subscribers
+
+ OCRepPayload* payload;
+ if (NSGetSyncPayload(sync, &payload) != NS_OK)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Failed to allocate payload"));
+ return NS_ERROR;
+ }
+
+ // Notify sync to subscribers
+
+ for(i = 0; i < whiteList->size; ++i)
+ {
+ printf("NS_ -------------------------------------------------------sync\n");
+ printf("NS_ whiteList->idList[%d] = %d\n", i, whiteList->idList[i]);
+ printf("NS_ -------------------------------------------------------sync\n");
+ }
+
+ OCStackResult ocstackResult = OCNotifyListOfObservers(rHandle, whiteList->idList, whiteList->size, payload, OC_LOW_QOS);
+
+ printf("NS_ sync ocstackResult = %d\n", ocstackResult);
+ if (ocstackResult != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, NOTIFICATION_TAG, "fail to send Sync");
+ OCRepPayloadDestroy(payload);
+ return NS_ERROR;
+
+ }
+ OCRepPayloadDestroy(payload);
+
+ return NS_OK;
+}
+
+void * NSNotificationSchedule(void *ptr)
+{
+ if (ptr == NULL)
+ {
+ OIC_LOG(DEBUG, NOTIFICATION_TAG, "Create NSNotifiactionSchedule");
+ }
+
+ while (NSIsRunning[NOTIFICATION_SCHEDULER])
+ {
+ sem_wait(&NSSemaphore[NOTIFICATION_SCHEDULER]);
+ pthread_mutex_lock(&NSMutex[NOTIFICATION_SCHEDULER]);
+
+ if (NSHeadMsg[NOTIFICATION_SCHEDULER] != NULL)
+ {
+ NSTask *node = NSHeadMsg[NOTIFICATION_SCHEDULER];
+ NSHeadMsg[NOTIFICATION_SCHEDULER] = node->nextTask;
+
+ switch (node->taskType)
+ {
+ case TASK_SEND_NOTIFICATION:
+ {
+ NSMessage * nsMsg = node->taskData;
+ NSSendMessage(nsMsg);
+ break;
+ }
+ case TASK_SEND_READ:
+ NSSendSync((NSSync*) node->taskData);
+ break;
+ case TASK_RECV_READ:
+ NSSendSync((NSSync*) node->taskData);
+ NSPushQueue(RESPONSE_SCHEDULER, TASK_CB_SYNC, node->taskData);
+ break;
+
+ default:
+ OIC_LOG(ERROR, NOTIFICATION_TAG, "Unknown type message");
+ break;
+
+ }
+ OICFree(node);
+ }
+
+ pthread_mutex_unlock(&NSMutex[NOTIFICATION_SCHEDULER]);
+
+ }
+ return NULL;
+}
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_NOTIFICATION_H_\r
+#define _NS_PROVIDER_NOTIFICATION_H_\r
+\r
+#include <ocstack.h>\r
+#include "logger.h"\r
+#include "NSQueueScheduler.h"\r
+#include "NSProviderListener.h"\r
+#include "NSProviderResource.h"\r
+#include "NSProviderCacheAdapter.h"\r
+\r
+NSResult NSRegisterResource();\r
+\r
+NSResult NSGetObsIdList(OCObservationId *list);\r
+\r
+uint32_t NSGetNumberOfObsList();\r
+\r
+NSResult NSPutNotificationMessage(NSMessage *msg, OCResourceHandle *rHandle);\r
+\r
+NSResult NSSendNotificationMessage(NSMessage *msg);\r
+\r
+#endif /* _NS_PROVIDER_NOTIFICATION_H_ */\r
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "NSProviderResource.h"
+
+const char* NSType = "oic.r.notification";
+const char* NSMessageType = "oic.r.notification.message";
+const char* NSSyncType = "oic.r.notification.sync";
+
+const char* NSInterface = "oic.if.baseline";
+const char* NSMessgeInterface = "oic.if.baseline.message";
+const char* NSSyncInterface = "oic.if.baseline.sync";
+
+const char* NSUri = "/notification";
+const char* NSMessageUri = "/notification/message";
+const char* NSSyncUri = "/notification/sync";
+
+/* Structure to represent notification resources */
+typedef struct
+{
+ OCResourceHandle handle;
+ int accepter;
+ char* message_uri;
+ char* sync_uri;
+} NSNotificationResource;
+
+typedef struct
+{
+ OCResourceHandle handle;
+ char* id;
+ char* title;
+ char* body;
+} NSMessageResource;
+
+typedef struct
+{
+ OCResourceHandle handle;
+ char* id;
+ char* state;
+ NSDevice device;
+} NSSyncResource;
+
+NSNotificationResource NotificationResource;
+NSMessageResource NotificationMessageResource;
+NSSyncResource NotificationSyncResource;
+
+NSResult NSCreateResource(char *uri)
+{
+ if (!uri)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, "Resource URI cannot be NULL");
+ return NS_ERROR;
+ }
+
+ if (strcmp(uri, NSUri) == 0)
+ {
+
+ NotificationResource.accepter = 0;
+ NotificationResource.message_uri = NSMessageUri;
+ NotificationResource.sync_uri = NSSyncUri;
+ NotificationResource.handle = NULL;
+
+ if (OCCreateResource(&NotificationResource.handle, NSType, NSInterface, NSUri,
+ NSEntityHandlerNotificationCb, NULL, OC_DISCOVERABLE) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to Create Notification Resource"));
+ return NS_ERROR;
+ }
+
+ printf("NotificationResource.handle = %u\n", NotificationResource.handle);
+
+
+ }
+ else if (strcmp(uri, NSMessageUri) == 0)
+ {
+
+ NotificationMessageResource.id = NULL;
+ NotificationMessageResource.title = NULL;
+ NotificationMessageResource.body = NULL;
+ NotificationMessageResource.handle = NULL;
+
+ if (OCCreateResource(&NotificationMessageResource.handle, NSMessageType, NSInterface,
+ NSMessageUri, NSEntityHandlerMessageCb, NULL, OC_OBSERVABLE) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to Create Notification Message Resource"));
+ return NS_ERROR;
+ }
+
+ printf("NotificationMessageResource.handle = %u\n", NotificationMessageResource.handle);
+
+
+ }
+ else if (strcmp(uri, NSSyncUri) == 0)
+ {
+ NotificationSyncResource.id = NULL;
+ NotificationSyncResource.state = NULL;
+ NotificationSyncResource.device;
+ NotificationSyncResource.handle = NULL;
+
+ if (OCCreateResource(&(NotificationSyncResource.handle), NSSyncType, NSInterface, NSSyncUri,
+ NSEntityHandlerSyncCb, NULL, OC_OBSERVABLE) != OC_STACK_OK)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to Create Notification Sync Resource"));
+ return NS_ERROR;
+ }
+
+ printf("NotificationSyncResource.handle = %u\n", NotificationSyncResource.handle);
+
+ }
+ else
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to create resource with invalid URI"));
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+NSResult NSRegisterResource()
+{
+ OIC_LOG(INFO, RESOURCE_TAG, "NSRegisterResource");
+
+ if (NSCreateResource(NSSyncUri) != NS_OK)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to register Sync Resource"));
+ return NS_ERROR;
+ }
+
+ if (NSCreateResource(NSMessageUri) != NS_OK)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to register Message Resource"));
+ return NS_ERROR;
+ }
+
+ if (NSCreateResource(NSUri) != NS_OK)
+ {
+ OIC_LOG(ERROR, RESOURCE_TAG, PCF("Fail to register Notification Resource"));
+ return NS_ERROR;
+ }
+
+ return NS_OK;
+}
+
+NSResult NSPutNotificationResource(int accepter, OCResourceHandle * handle)
+{
+ NotificationResource.accepter = accepter;
+ NotificationResource.message_uri = NSMessageUri;
+ NotificationResource.sync_uri = NSSyncUri;
+
+ *handle = NotificationResource.handle;
+
+ return NS_OK;
+}
+
+NSResult NSPutMessageResource(NSMessage *msg, OCResourceHandle * handle)
+{
+ OIC_LOG(INFO, RESOURCE_TAG, "Put notification message to Resource");
+
+ if(msg != NULL)
+ {
+ printf("msg is not null\n");
+ NotificationMessageResource.id = strdup(msg->mId);
+ NotificationMessageResource.title = strdup(msg->mTitle);
+ NotificationMessageResource.body = strdup(msg->mContentText);
+ }
+ else
+ {
+ printf("msg is null\n");
+ }
+
+ *handle = NotificationMessageResource.handle;
+
+ return NS_OK;
+}
+
+NSResult NSPutSyncResource(NSSync *sync, OCResourceHandle * handle)
+{
+ OIC_LOG(INFO, RESOURCE_TAG, "Put notification sync to Resource");
+
+ *handle = NotificationSyncResource.handle;
+
+ return NS_OK;
+}
+
+const char* NSGetNotificationUri()
+{
+ return NSUri;
+}
+
+const char* NSGetNotificationMessageUri()
+{
+ return NSMessageUri;
+}
+
+const char* NSGetNotificationSyncUri()
+{
+ return NSSyncUri;
+}
+
+NSResult NSCopyString(char** targetString, const char* sourceString)
+{
+ if (sourceString)
+ {
+ *targetString = (char *) malloc(strlen(sourceString) + 1);
+
+ if (*targetString)
+ {
+ strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
+ return NS_SUCCESS;
+ }
+ }
+
+ return NS_FAIL;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2016 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#ifndef _NS_PROVIDER_RESOURCE_H_
+#define _NS_PROVIDER_RESOURCE_H_
+
+#include <ocstack.h>
+#include "logger.h"
+#include "NSCommon.h"
+#include "NSProviderListener.h"
+
+NSResult NSCreateResource(char *uri);
+
+NSResult NSRegisterResource();
+
+NSResult NSPutNotificationResource(int accepter, OCResourceHandle * handle);
+
+NSResult NSPutMessageResource(NSMessage *msg, OCResourceHandle * handle);
+
+NSResult NSPutSyncResource(NSSync *sync, OCResourceHandle * handle);
+
+const char* NSGetNotificationMessageUri();
+
+const char* NSGetNotificationSyncUri();
+
+const char* NSGetNotificationUri();
+
+NSResult NSCopyString(char** targetString, const char* sourceString);
+
+#endif /* _NS_PROVIDER_RESOURCE_H_ */
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#include "NSProviderSubscription.h"\r
+\r
+NSResult NSSetSubscriptionAcceptPolicy(NSAccessPolicy policy)\r
+{\r
+ if (policy == NS_ACCEPTER_PROVIDER)\r
+ {\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Place Provider as a subscription accepter");\r
+ }\r
+ else if (policy == NS_ACCEPTER_CONSUMER)\r
+ {\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Place Consumer as a subscription accepter");\r
+ }\r
+\r
+ NSSubscriptionAccepter = policy;\r
+\r
+ return NS_OK;\r
+}\r
+\r
+int NSGetSubscriptionAccepter()\r
+{\r
+ return NSSubscriptionAccepter;\r
+}\r
+\r
+NSResult NSSendAccessPolicyResponse(OCEntityHandlerRequest *entityHandlerRequest)\r
+{\r
+ OIC_LOG(DEBUG, NOTIFICATION_TAG, "Send Notification Policy to consumer");\r
+\r
+ // put notification resource\r
+ OCResourceHandle notificationResourceHandle;\r
+ if(NSPutNotificationResource(NSGetSubscriptionAccepter(), ¬ificationResourceHandle) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, PCF("Failed to put notification resource"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ // make response for the Get Request\r
+ OCEntityHandlerResponse response;\r
+ response.numSendVendorSpecificHeaderOptions = 0;\r
+ memset(response.sendVendorSpecificHeaderOptions, 0,\r
+ sizeof response.sendVendorSpecificHeaderOptions);\r
+ memset(response.resourceUri, 0, sizeof response.resourceUri);\r
+\r
+ OCRepPayload* payload = OCRepPayloadCreate();\r
+ //response.payload = OCRepPayloadCreate();\r
+ if (!payload)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, PCF("Failed to allocate Payload"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ OCRepPayloadSetUri(payload, NSGetNotificationUri());\r
+ OCRepPayloadSetPropInt(payload, NS_ATTRIBUTE_POLICY, NSGetSubscriptionAccepter());\r
+ OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_MESSAGE, NSGetNotificationMessageUri());\r
+ OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_SYNC, NSGetNotificationSyncUri());\r
+\r
+ response.requestHandle = entityHandlerRequest->requestHandle;\r
+ response.resourceHandle = entityHandlerRequest->resource;\r
+ response.persistentBufferFlag = 0;\r
+ response.ehResult = OC_EH_OK;\r
+ response.payload = (OCPayload *)payload;\r
+\r
+\r
+ // Send Response\r
+ if (OCDoResponse(&response) != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, PCF("Fail to send response"));\r
+ return NS_ERROR;\r
+ }\r
+ OCRepPayloadDestroy(payload);\r
+\r
+ return NS_OK;\r
+}\r
+\r
+void NSHandleSubscription(OCEntityHandlerRequest *entityHandlerRequest, int state)\r
+{\r
+\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Start to subscription process");\r
+\r
+ printf("state = 0 \n");\r
+\r
+ // write consumer info to cache\r
+ if(state == 0)\r
+ {\r
+\r
+ printf("state = 0 - 1\n");\r
+\r
+ if (NSProviderWriteToCache(NS_CONSUMER_BLACKLIST, entityHandlerRequest->obsInfo.obsId, state) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, PCF("fail to write consumer black list"));\r
+ }\r
+ printf("state = 0 - 2\n");\r
+ // check access policy\r
+ if (NSGetSubscriptionAccepter() == NS_ACCEPTER_PROVIDER)\r
+ {\r
+ // OCDevAddr --> NSConsumer\r
+ printf("before NSGetSubscriptionAccepter() == NS_ACCEPTER_PROVIDER)\n");\r
+ NSAskAcceptanceToUser(entityHandlerRequest);\r
+ printf("After NSGetSubscriptionAccepter() == NS_ACCEPTER_PROVIDER)\n");\r
+ }\r
+ else if (NSGetSubscriptionAccepter() == NS_ACCEPTER_CONSUMER)\r
+ {\r
+ printf("state = 0 - 3\n");\r
+ NSSendSubscriptionResponse(entityHandlerRequest, NS_ACCEPTER_CONSUMER, true);\r
+ }\r
+ }\r
+ else if(state == 1)\r
+ {\r
+ printf("state = 1 - 0\n");\r
+ if (NSProviderWriteToCache(NS_CONSUMER_WHITELIST, entityHandlerRequest->obsInfo.obsId, state) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, PCF("fail to write consumer white list"));\r
+ }\r
+ printf("state = 1 - 1\n");\r
+ }\r
+}\r
+\r
+void NSHandleUnsubscription(OCEntityHandlerRequest *entityHandlerRequest)\r
+{\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Start to unsubscription process");\r
+\r
+ // ProcessObserveUnregister (entityHandlerRequest);\r
+\r
+ // write consumer info to cache\r
+ if (NSProviderWriteToCache(NS_CONSUMER_BLACKLIST, entityHandlerRequest->devAddr) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, "fail to write consumer black list");\r
+ }\r
+}\r
+\r
+void NSAskAcceptanceToUser(OCEntityHandlerRequest *entityHandlerRequest)\r
+{\r
+ OIC_LOG(DEBUG, SUBSCRIPTION_TAG, "Ask for user to Allow or Deny");\r
+\r
+ NSPushQueue(RESPONSE_SCHEDULER, TASK_CB_SUBSCRIPTION, entityHandlerRequest);\r
+ // one queue is required for response callback to ask subscription allowance\r
+}\r
+\r
+NSResult NSSendResponse(int observeId, bool accepted)\r
+{\r
+\r
+ OCRepPayload* payload = OCRepPayloadCreate();\r
+ if (!payload)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, PCF("Failed to allocate Payload"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ OCResourceHandle rHandle;\r
+ if (NSPutMessageResource(NULL, &rHandle) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, NOTIFICATION_TAG, PCF("Fail to put notification resource"));\r
+ return NS_ERROR;\r
+ }\r
+\r
+ OCRepPayloadSetUri(payload, NSGetNotificationMessageUri());\r
+ OCRepPayloadSetPropString(payload, NS_ATTRIBUTE_ID, "0000-0000-0000-0000");\r
+ OCRepPayloadSetPropBool(payload, NS_ATTRIBUTE_ACCPETANCE, accepted);\r
+\r
+ if (OCNotifyListOfObservers(rHandle, &observeId, 1, payload, OC_HIGH_QOS) != OC_STACK_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, "fail to send Acceptance");\r
+ OCRepPayloadDestroy(payload);\r
+ return NS_ERROR;\r
+\r
+ }\r
+ OCRepPayloadDestroy(payload);\r
+\r
+ return NS_OK;\r
+}\r
+\r
+NSResult NSSendSubscriptionResponse(OCEntityHandlerRequest *entityHandlerRequest,\r
+ NSAccessPolicy accepter, bool accepted)\r
+{\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Send ACCEPT message to consumer");\r
+\r
+ if (!entityHandlerRequest)\r
+ {\r
+ OIC_LOG (ERROR, LISTENER_TAG, "Invalid request pointer");\r
+ return OC_EH_ERROR;\r
+ }\r
+\r
+ // write consumer info to cache\r
+\r
+ printf("accepted 1 \n");\r
+ if (accepted)\r
+ {\r
+ if (NSProviderWriteToCache(NS_CONSUMER_WHITELIST, entityHandlerRequest->obsInfo.obsId) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, "fail to write consumer white list");\r
+ }\r
+ }\r
+\r
+ NSSendResponse(&entityHandlerRequest->obsInfo.obsId, accepted);\r
+\r
+ return NS_OK;\r
+\r
+}\r
+\r
+void * NSSubScriptionSchedule(void *ptr)\r
+{\r
+\r
+ if (ptr == NULL)\r
+ {\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Create NSSubscriptionSchedule");\r
+ }\r
+\r
+ while (NSIsRunning[SUBSCRIPTION_SCHEDULER])\r
+ {\r
+ sem_wait(&NSSemaphore[SUBSCRIPTION_SCHEDULER]);\r
+ pthread_mutex_lock(&NSMutex[SUBSCRIPTION_SCHEDULER]);\r
+\r
+ if (NSHeadMsg[SUBSCRIPTION_SCHEDULER] != NULL)\r
+ {\r
+ NSTask *node = NSHeadMsg[SUBSCRIPTION_SCHEDULER];\r
+ NSHeadMsg[SUBSCRIPTION_SCHEDULER] = node->nextTask;\r
+\r
+ switch (node->taskType)\r
+ {\r
+\r
+ case TASK_SEND_POLICY:\r
+\r
+ NSSendAccessPolicyResponse((OCEntityHandlerRequest*) node->taskData);\r
+ break;\r
+\r
+ case TASK_RECV_SUBSCRIPTION:\r
+ printf("before TASK_RECV_SUBSCRIPTION:\n");\r
+ NSHandleSubscription((OCEntityHandlerRequest*) node->taskData, 0);\r
+ printf("after TASK_RECV_SUBSCRIPTION:\n");\r
+ break;\r
+\r
+ case TASK_RECV_UNSUBSCRIPTION:\r
+\r
+ NSHandleUnsubscription((OCEntityHandlerRequest*) node->taskData);\r
+ break;\r
+\r
+ case TASK_SEND_ALLOW:\r
+ {\r
+ NSConsumer * consumer = (NSConsumer *)node->taskData;\r
+ int * pObId = (int *)consumer->mUserData;\r
+\r
+ printf("observer ID = %d\n", *pObId);\r
+\r
+ if (NSProviderWriteToCache(NS_CONSUMER_WHITELIST, *pObId, 0) != NS_OK)\r
+ {\r
+ OIC_LOG(ERROR, SUBSCRIPTION_TAG, "fail to write consumer white list");\r
+ }\r
+ NSSendResponse(*pObId, true);\r
+\r
+ break;\r
+ }\r
+ case TASK_SEND_DENY:\r
+\r
+// NSSendSubscriptionResponse((OCEntityHandlerRequest*) node->taskData,\r
+// NS_ACCEPTER_PROVIDER, false);\r
+ break;\r
+\r
+ case TASK_SYNC_SUBSCRIPTION:\r
+ NSHandleSubscription((OCEntityHandlerRequest*) node->taskData, 1);\r
+ break;\r
+\r
+ }\r
+ OICFree(node);\r
+ }\r
+\r
+ pthread_mutex_unlock(&NSMutex[SUBSCRIPTION_SCHEDULER]);\r
+\r
+ }\r
+ return NULL;\r
+}\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_SUBSCRIPTION_H_\r
+#define _NS_PROVIDER_SUBSCRIPTION_H_\r
+\r
+#include "logger.h"\r
+#include "ocstack.h"\r
+#include "ocpayload.h"\r
+#include "NSCommon.h"\r
+#include "NSConstants.h"\r
+#include "NSQueueScheduler.h"\r
+#include "NSProviderResource.h"\r
+\r
+static NSAccessPolicy NSSubscriptionAccepter;\r
+\r
+NSResult NSSetSubscriptionAcceptPolicy(NSAccessPolicy policy);\r
+int NSGetSubscriptionAccepter();\r
+NSResult NSSendAccessPolicyResponse(OCEntityHandlerRequest *entityHandlerRequest);\r
+void NSHandleSubscription(OCEntityHandlerRequest *entityHandlerRequest, int state);\r
+void NSHandleUnsubscription(OCEntityHandlerRequest *entityHandlerRequest);\r
+void NSAskAcceptanceToUser(OCEntityHandlerRequest *entityHandlerRequest);\r
+NSResult NSSendSubscriptionResponse(OCEntityHandlerRequest *entityHandlerRequest,\r
+ NSAccessPolicy accepter, bool accepted);\r
+\r
+#endif /* _NS_PROVIDER_SUBSCRIPTION_H_ */\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+#include "NSProviderSystem.h"\r
+\r
+static NSConnectionState NSProviderConnectionState;\r
+\r
+void NSSetProviderConnectionState(NSConnectionState state)\r
+{\r
+ OIC_LOG(INFO, SUBSCRIPTION_TAG, "Change Connection State");\r
+\r
+ NSProviderConnectionState = state;\r
+}\r
+\r
+NSConnectionState NSGetProviderConnectionState()\r
+{\r
+ return NSProviderConnectionState;\r
+}\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2016 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+#ifndef _NS_PROVIDER_SYSTEM__H_\r
+#define _NS_PROVIDER_SYSTEM__H_\r
+\r
+#include "logger.h"\r
+#include "NSCommon.h"\r
+#include "NSConstants.h"\r
+\r
+void NSSetProviderConnectionState(NSConnectionState state);\r
+NSConnectionState NSGetProviderConnectionState();\r
+\r
+#endif /* _NS_PROVIDER_SYSTEM__H_ */\r
+++ /dev/null
-Initial commit for notification service folder structure
-