Merge "Replaced sprintf with snprintf in the sdk to avoid potential buffer overflows"
authorsudarshan prasad <sudarshan.prasad@intel.com>
Fri, 19 Dec 2014 22:38:52 +0000 (14:38 -0800)
committerGerrit Code Review <gerrit@oicreview.vlan14.01.org>
Fri, 19 Dec 2014 22:38:52 +0000 (14:38 -0800)
170 files changed:
.gitignore
SConstruct
build_common/SConscript
build_common/arduino/SConscript [changed mode: 0755->0644]
resource/csdk/SConscript
resource/csdk/libcoap-4.1.1/net.c
resource/csdk/libcoap-4.1.1/sec/netdtls.c
resource/csdk/makefile
resource/csdk/occoap/include/occoaphelper.h
resource/csdk/occoap/src/occoap.c
resource/csdk/occoap/src/occoaphelper.c
resource/csdk/stack/include/internal/ocresource.h
resource/csdk/stack/include/internal/ocresourcehandler.h
resource/csdk/stack/include/internal/oicgroup.h [new file with mode: 0644]
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/include/ocstackconfig.h
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.h
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocresource.c
resource/csdk/stack/src/ocstack.c
resource/csdk/stack/src/oicgroup.c [new file with mode: 0644]
resource/examples/SConscript
resource/examples/devicediscoveryclient.cpp [new file with mode: 0644]
resource/examples/devicediscoveryserver.cpp [new file with mode: 0644]
resource/examples/groupclient.cpp [new file with mode: 0755]
resource/examples/groupserver.cpp [new file with mode: 0755]
resource/examples/lightserver.cpp [new file with mode: 0755]
resource/examples/makefile [changed mode: 0644->0755]
resource/examples/presenceclient.cpp
resource/examples/presenceserver.cpp
resource/include/IClientWrapper.h
resource/include/IServerWrapper.h
resource/include/InProcClientWrapper.h
resource/include/InProcServerWrapper.h
resource/include/OCApi.h
resource/include/OCPlatform.h
resource/include/OCPlatform_impl.h
resource/include/OutOfProcClientWrapper.h
resource/include/OutOfProcServerWrapper.h
resource/include/StringConstants.h
resource/src/InProcClientWrapper.cpp
resource/src/InProcServerWrapper.cpp
resource/src/OCException.cpp
resource/src/OCPlatform.cpp
resource/src/OCPlatform_impl.cpp
resource/src/OCUtilities.cpp
service/docs/Control Manager-Programmer's guide.pdf [new file with mode: 0644]
service/docs/Getting Started_IoTivity Services_20141218.pdf [new file with mode: 0755]
service/docs/Getting Started_SSM_PPM_Things Manager_NM_20141218.pdf [new file with mode: 0755]
service/docs/IoTivity Services_20141216.pdf [new file with mode: 0644]
service/docs/Notification Manager - Programmer's guide.pdf [new file with mode: 0644]
service/docs/PPM - Programmer's Guide_20141218.pdf [new file with mode: 0755]
service/docs/SSM - Programmer's guide_20141216.pdf [new file with mode: 0755]
service/docs/Things Manager - Programmer's guide_M2_SDK_APIs.pdf [new file with mode: 0644]
service/protocol-plugin/build/linux/Makefile
service/protocol-plugin/plugin-manager/src/Config.cpp
service/protocol-plugin/plugin-manager/src/PluginManager.cpp
service/protocol-plugin/plugin-manager/src/PluginManager.h
service/protocol-plugin/readme
service/protocol-plugin/sample-app/linux/mqtt/mqttclient.cpp
service/soft-sensor-manager/Readme.txt
service/soft-sensor-manager/SConscript
service/soft-sensor-manager/SDK/cpp/build/linux/Makefile [moved from service/soft-sensor-manager/SDK/build/linux/Makefile with 76% similarity]
service/soft-sensor-manager/SDK/cpp/include/SSMInterface.h [new file with mode: 0644]
service/soft-sensor-manager/SDK/cpp/src/InprocSSMCore.cpp [moved from service/soft-sensor-manager/SDK/src/InprocSSMCore.cpp with 100% similarity]
service/soft-sensor-manager/SDK/include/ISSMClientListener.h [deleted file]
service/soft-sensor-manager/SDK/include/SSMClient.h [deleted file]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/CoreController.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/DataReader.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IQueryEngineEvent.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IReportReceiver.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/ModelData.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/QueryEngine.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/SSMInterface.java [new file with mode: 0644]
service/soft-sensor-manager/SDK/src/SSMClient.cpp [deleted file]
service/soft-sensor-manager/SSMCore/build/linux/Makefile
service/soft-sensor-manager/SSMCore/include/SSMInterface.h
service/soft-sensor-manager/SSMCore/src/Common/ObjectManager.h
service/soft-sensor-manager/SSMCore/src/QueryProcessor/ContextModel.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/EvaluationEngine.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/PropagationEngine.cpp
service/soft-sensor-manager/SSMCore/src/QueryProcessor/QueryEngine.cpp
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMResourceServer.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextExecutor.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ContextRepository.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ResourceFinder.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ResourceFinder.h
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/readme.txt [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile [moved from service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/Makefile with 100% similarity]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/oic_lanLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/readme.txt [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/SConscript
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/build/Makefile
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/include/SSMTestApp.h
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/src/SSMTestApp.cpp
service/soft-sensor-manager/SampleApp/linux/THSensorApp/include/ThingResourceServer.h
service/soft-sensor-manager/SampleApp/linux/THSensorApp/src/ThingResourceServer.cpp
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/include/ThingResourceServer1.h
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/src/ThingResourceServer1.cpp
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-test.cpp
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/SoftSensorDescription.xml [deleted file]
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/build/linux/Makefile
service/soft-sensor-manager/SoftSensorPlugin/SoftSensorDescription.xml [new file with mode: 0644]
service/soft-sensor-manager/build/arduino/local.properties
service/soft-sensor-manager/build/linux/environment.mk
service/soft-sensor-manager/doc/SSM Developer s guide_v0.1.pdf [deleted file]
service/soft-sensor-manager/doc/SSM Getting Started_v0.1.pdf [deleted file]
service/things-manager/SConscript
service/things-manager/build/linux/Makefile [deleted file]
service/things-manager/build/linux/makefile [new file with mode: 0644]
service/things-manager/sampleapp/SConscript
service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.h [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.h [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/FactorySetCollection.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/FactorySetCollection.h [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/SConscript [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/bootstrapserver.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/con-client.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/con-server.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/configuration/makefile [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupaction/SConscript [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupaction/bookmark.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupaction/groupserver.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupaction/lightserver.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupaction/makefile [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupsyncaction/SConscript [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupsyncaction/group.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupsyncaction/makefile [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupsyncaction/musicplayer.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupsyncaction/phone.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/groupsyncaction/speaker.cpp [new file with mode: 0644]
service/things-manager/sampleapp/linux/makefile [new file with mode: 0644]
service/things-manager/sampleapp/linux/tgmclient/SConscript [deleted file]
service/things-manager/sampleapp/linux/tgmclient/makefile [deleted file]
service/things-manager/sampleapp/linux/tgmclient/tgmsdkclient.cpp [deleted file]
service/things-manager/sdk/build/linux/Makefile
service/things-manager/sdk/inc/TGMClient.h [deleted file]
service/things-manager/sdk/inc/ThingsManager.h [new file with mode: 0644]
service/things-manager/sdk/src/GroupManager.cpp [new file with mode: 0644]
service/things-manager/sdk/src/GroupManager.h [new file with mode: 0644]
service/things-manager/sdk/src/GroupSynchronization.cpp [new file with mode: 0644]
service/things-manager/sdk/src/GroupSynchronization.h [new file with mode: 0644]
service/things-manager/sdk/src/TGMClient.cpp [deleted file]
service/things-manager/sdk/src/ThingsConfiguration.cpp [new file with mode: 0644]
service/things-manager/sdk/src/ThingsConfiguration.h [new file with mode: 0644]
service/things-manager/sdk/src/ThingsDiagnostics.cpp [new file with mode: 0644]
service/things-manager/sdk/src/ThingsDiagnostics.h [new file with mode: 0644]
service/things-manager/sdk/src/ThingsManager.cpp [new file with mode: 0644]

index a5463f0..1db09ad 100644 (file)
@@ -44,3 +44,10 @@ dependencies/
 
 #ignore various swap files
 *.swp
+
+# Ignore SCons generated files and directories
+.scon*
+config.log
+os
+out/
+platform
index fd1b034..92eac38 100644 (file)
@@ -28,7 +28,7 @@ build_dir = env.get('BUILD_DIR')
 SConscript(build_dir + 'resource/SConscript')
 
 # Build 'service' sub-project
-#SConscript(build_dir + 'service/SConscript')
+SConscript(build_dir + 'service/SConscript')
 
 # Append targets information to the help information, to see help info, execute command line:
 #     $ scon [options] -h
index c6708e4..dd1fb3b 100644 (file)
@@ -7,7 +7,7 @@ import platform
 
 # Map of host os and allowed target os (host: allowed target os)
 host_target_map = {
-               'linux': ['linux', 'android', 'arduino'],
+               'linux': ['linux', 'android', 'arduino', 'yocto'],
                'windows': ['windows', 'winrt', 'android', 'arduino'],
                'darwin': ['darwin', 'ios', 'android', 'arduino'],
                }
@@ -21,6 +21,7 @@ os_arch_map = {
                'darwin': ['i386', 'x86_64'],
                'ios': ['i386', 'x86_64', 'armv7', 'armv7s', 'arm64'],
                'arduino': ['avr', 'arm'],
+                'yocto': ['x86', 'x86_64'],
                }
 
 host = platform.system().lower()
@@ -167,8 +168,60 @@ env.SetDir(env.GetLaunchDir())
 
 Export('env')
 
-# Load config of target os
-env.SConscript(target_os + '/SConscript')
+######################################################################
+# Link scons to Yocto cross-toolchain ONLY when target_os is yocto
+######################################################################
+if target_os == "yocto":
+    '''
+    This code injects Yocto cross-compilation tools+flags into scons' 
+    build environment in order to invoke the relevant tools while 
+    performing a build.
+    '''
+    import os.path
+    try:
+        CC = os.environ['CC']
+        target_prefix = CC.split()[0]
+        target_prefix = target_prefix[:len(target_prefix)-3]
+        tools = {"CC" : target_prefix+"gcc",
+                "CXX" : target_prefix+"g++",
+                "AS" : target_prefix+"as",
+                "LD" : target_prefix+"ld",
+                "GDB" : target_prefix+"gdb",
+                "STRIP" : target_prefix+"strip",
+                "RANLIB" : target_prefix+"ranlib",
+                "OBJCOPY" : target_prefix+"objcopy",
+                "OBJDUMP" : target_prefix+"objdump",
+                "AR" : target_prefix+"ar",
+                "NM" : target_prefix+"nm",
+                "M4" : "m4",
+                "STRINGS": target_prefix+"strings"}
+        PATH = os.environ['PATH'].split(os.pathsep)
+        for tool in tools:
+            if tool in os.environ:
+                for path in PATH:
+                    if os.path.isfile(os.path.join(path, tools[tool])):
+                        env[tool] = os.path.join(path, os.environ[tool])
+                        break
+    except:
+        print "ERROR in Yocto cross-toolchain environment"
+        Exit(1)
+    '''
+    Now reset TARGET_OS to linux so that all linux specific build configurations
+    hereupon apply for the entirety of the build process.
+    '''
+    env['TARGET_OS'] = 'linux'
+    '''
+    We want to preserve debug symbols to allow BitBake to generate both DEBUG and
+    RELEASE packages for OIC. 
+    '''
+    env['CCFLAGS'].append('-g')
+    Export('env')
+else:
+    '''
+    If target_os is not Yocto, continue with the regular build process
+    '''
+    # Load config of target os
+    env.SConscript(target_os + '/SConscript')
 
 # Delete the temp files of configuration
 if env.GetOption('clean'):
old mode 100755 (executable)
new mode 100644 (file)
index 5df1507..6de4c2d 100644 (file)
@@ -68,9 +68,10 @@ liboctbstack_src = [
        OCTBSTACK_SRC + 'occlientcb.c',
        OCTBSTACK_SRC + 'ocresource.c',
        OCTBSTACK_SRC + 'ocobserve.c',
-        OCTBSTACK_SRC + 'ocserverrequest.c',
+    OCTBSTACK_SRC + 'ocserverrequest.c',
        OCTBSTACK_SRC + 'occollection.c',
-       OCTBSTACK_SRC + 'ocsecurity.c'
+       OCTBSTACK_SRC + 'ocsecurity.c',
+    OCTBSTACK_SRC + 'oicgroup.c'
        ]
 if target_os == 'arduino':
        liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src)
index 4fce8f9..d36b0e2 100644 (file)
@@ -997,9 +997,9 @@ int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id,
 
     if (!queue || !*queue)
         return 0;
+    debug("*** looking for transaction %u == %u\n", id, (*queue)->id);
 
     /* replace queue head if PDU's time is less than head's time */
-
     if (id == (*queue)->id) { /* found transaction */
         *node = *queue;
         *queue = (*queue)->next;
index 1535670..e90e64b 100644 (file)
@@ -406,7 +406,7 @@ int coap_dtls_init(coap_context_t *ctx, uint8_t ipAddr[]) {
     ret = 0;
 
 exit:
-    if (ret == -1 && coap_dtls_ctx) {
+    if (ret == -1) {
         coap_dtls_deinit(ctx);
     }
     return ret;
@@ -420,18 +420,21 @@ exit:
  *
  */
 void coap_dtls_deinit(coap_context_t *ctx) {
-    if (!ctx)
+
+    if (!ctx || !ctx->coap_dtls_ctx)
         return;
 
     coap_dtls_context_t *coap_dtls_ctx = ctx->coap_dtls_ctx;
 
-    if (coap_dtls_ctx) {
-        coap_delete_all(coap_dtls_ctx->cachedqueue);
-        if (ctx->sockfd_dtls != -1)
-            OCClose(ctx->sockfd_dtls);
-        dtls_free_context(coap_dtls_ctx->dtls_ctx);
-        coap_free(coap_dtls_ctx);
-    }
+    coap_delete_all(coap_dtls_ctx->cachedqueue);
+
+    dtls_free_context(coap_dtls_ctx->dtls_ctx);
+    coap_dtls_ctx->dtls_ctx = NULL;
+
+    if (ctx->sockfd_dtls != -1)
+        OCClose(ctx->sockfd_dtls);
+
+    coap_free(coap_dtls_ctx);
     ctx->coap_dtls_ctx = NULL;
 }
 
index 238a65d..ca77f30 100644 (file)
@@ -135,6 +135,7 @@ OCTBSTACK_SOURCES   += $(OCTBSTACK_SRC)/ocresource.c
 OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocobserve.c
 OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocserverrequest.c
 OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/occollection.c
+OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/oicgroup.c
 OCTBSTACK_SOURCES      += $(OCTBSTACK_SRC)/ocsecurity.c
 
 SOURCES                        := $(CJSON_SOURCES)
index 2dc687e..8e36776 100644 (file)
 #define MAX_URI_QUERY_BUF_SIZE ((MAX_URI_LENGTH) >= (MAX_QUERY_LENGTH) ?\
                             (MAX_URI_LENGTH) : (MAX_QUERY_LENGTH))
 
+#define COAP_WK_IPAddr_0 (224)
+#define COAP_WK_IPAddr_1 (0)
+#define COAP_WK_IPAddr_2 (1)
+#define COAP_WK_IPAddr_3 (187)
+
 // checks if optionID is within vendor specific range
 OCStackResult isVendorSpecific(uint16_t optionID);
 
@@ -49,7 +54,7 @@ OCStackResult isVendorSpecific(uint16_t optionID);
 uint8_t OCToCoAPResponseCode(OCStackResult result);
 
 //Convert OCQualityOfService to coap NON vs CON
-uint8_t OCToCoAPQoS(OCQualityOfService qos);
+uint8_t OCToCoAPQoS(OCQualityOfService qos, uint8_t * ipAddr);
 
 // Convert CoAP code to OCStack code
 OCStackResult CoAPToOCResponseCode(uint8_t coapCode);
index 168e0bc..427ebf0 100644 (file)
@@ -55,7 +55,6 @@
 // Private Variables
 //=============================================================================
 
-static uint8_t coapWKIpAddr[] = { 224, 0, 1, 187 };
 static coap_context_t *gCoAPCtx = NULL;
 
 //=============================================================================
@@ -228,7 +227,8 @@ static void HandleCoAPRequests(struct coap_context_t *ctx,
     if(requestResult == OC_STACK_VIRTUAL_DO_NOT_HANDLE ||
             requestResult == OC_STACK_OK ||
             requestResult == OC_STACK_RESOURCE_CREATED ||
-            requestResult == OC_STACK_RESOURCE_DELETED)
+            requestResult == OC_STACK_RESOURCE_DELETED ||
+            requestResult == OC_STACK_INVALID_DEVICE_INFO)
     {
         goto exit;
     }
@@ -675,8 +675,8 @@ OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode) {
 
     // To allow presence notification work we need to init socket gCoAPCtx->sockfd_wellknown
     // for servers as well as clients
-    OCBuildIPv4Address(coapWKIpAddr[0], coapWKIpAddr[1], coapWKIpAddr[2],
-            coapWKIpAddr[3], COAP_DEFAULT_PORT, &mcastAddr);
+    OCBuildIPv4Address(COAP_WK_IPAddr_0, COAP_WK_IPAddr_1, COAP_WK_IPAddr_2,
+            COAP_WK_IPAddr_3, COAP_DEFAULT_PORT, &mcastAddr);
     VERIFY_SUCCESS(
             coap_join_wellknown_group(gCoAPCtx,
                     (coap_address_t* )&mcastAddr), 0);
@@ -753,7 +753,7 @@ OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPTo
         OC_LOG_V(DEBUG, TAG, "secure uri %d", uri.secure);
     }
 
-    coapMsgType = OCToCoAPQoS(qos);
+    coapMsgType = OCToCoAPQoS(qos, ipAddr);
 
     // Decide method type
     switch (method) {
index 966bd79..1727c26 100644 (file)
@@ -90,8 +90,13 @@ uint8_t OCToCoAPResponseCode(OCStackResult result)
     return ret;
 }
 
-uint8_t OCToCoAPQoS(OCQualityOfService qos)
+uint8_t OCToCoAPQoS(OCQualityOfService qos, uint8_t * ipAddr)
 {
+    if(ipAddr[0] == COAP_WK_IPAddr_0 && ipAddr[1] == COAP_WK_IPAddr_1 &&
+            ipAddr[2] == COAP_WK_IPAddr_2 && ipAddr[3] == COAP_WK_IPAddr_3)
+    {
+        return COAP_MESSAGE_NON;
+    }
     switch (qos)
     {
         case OC_HIGH_QOS:
index 542cfb6..bbd652b 100644 (file)
@@ -49,9 +49,42 @@ typedef enum {
     STACK_IF_DEFAULT = 0,
     STACK_IF_LL,
     STACK_IF_BATCH,
+    STACK_IF_GROUP,
     STACK_IF_INVALID
 } OCStackIfTypes;
 
+// following structure will be created in occollection.
+typedef struct occapability {
+    struct occapability* next;
+
+    char *capability;           // It is a name about resource capability.
+    char *status;               // It is mean status of capability.
+} OCCapability;
+
+
+// following structure will be created in occollection.
+typedef struct ocaction {
+    struct ocaction *next;
+
+    // Target Uri.
+    // It will be used to execute the action.
+    char *resourceUri;
+
+    OCCapability* head;
+} OCAction;
+
+// following structure will be created in occollection.
+typedef struct ocactionset {
+
+    struct ocactionset *next;
+
+    char *actionsetName;
+
+    OCAction* head;
+} OCActionSet;
+
+
+
 typedef struct resourcetype_t {
     struct resourcetype_t *next; // linked list; for multiple types on resource
 
@@ -116,6 +149,8 @@ typedef struct rsrc_t {
     /* method_t methods; */
     // Sequence number for observable resources. Per the CoAP standard it is a 24 bit value.
     uint32_t sequenceNum;
+    // Pointer of ActionSet which to support group action.
+    OCActionSet *actionsetHead;
 } OCResource;
 
 
index e5a24bc..f56769c 100644 (file)
 #define OC_RSRVD_RESOURCE_TYPE          "rt"
 #define OC_RSRVD_RESOURCE_TYPE_PRESENCE "core.presence"
 #define OC_RSRVD_INTERFACE              "if"
+#define OC_RSRVD_DEVICE_ID              "di"
+#define OC_RSRVD_DEVICE_NAME            "dn"
 #define OC_RSRVD_INTERFACE_DEFAULT      "oc.mi.def"
 #define OC_RSRVD_INTERFACE_LL           "oc.mi.ll"
 #define OC_RSRVD_INTERFACE_BATCH        "oc.mi.b"
+#define OC_RSRVD_INTERFACE_GROUP        "oc.mi.c"
+
+
 #define OC_RSRVD_OBSERVABLE             "obs"
 #define OC_RSRVD_SECURE                 "sec"
 #define OC_RSRVD_HOSTING_PORT           "port"
@@ -50,7 +55,9 @@
 typedef enum {
     STACK_RES_DISCOVERY_NOFILTER = 0,
     STACK_RES_DISCOVERY_IF_FILTER,
-    STACK_RES_DISCOVERY_RT_FILTER
+    STACK_RES_DISCOVERY_RT_FILTER,
+    STACK_DEVICE_DISCOVERY_DI_FILTER,
+    STACK_DEVICE_DISCOVERY_DN_FILTER
 } StackQueryTypes;
 
 typedef enum {
@@ -77,6 +84,10 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
 OCStackResult
 ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request);
 
+OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo);
+
+void DeleteDeviceInfo();
+
 OCStackResult
 BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
                         char *filterValue, char * out, uint16_t *remaining);
diff --git a/resource/csdk/stack/include/internal/oicgroup.h b/resource/csdk/stack/include/internal/oicgroup.h
new file mode 100644 (file)
index 0000000..2493fba
--- /dev/null
@@ -0,0 +1,57 @@
+//******************************************************************
+//
+// Copyright 2014 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 OIC_GROUP_H
+#define OIC_GROUP_H
+
+#include "ocstack.h"
+#include "ocstackinternal.h"
+
+void AddCapability(OCCapability** head, OCCapability* node);
+
+void AddAction(OCAction** head, OCAction* node);
+
+void AddActionSet(OCActionSet **head, OCActionSet* node);
+
+void DeleteCapability(OCCapability *del);
+
+void DeleteAction(OCAction** action);
+
+void DeleteActionSet(OCActionSet** actionset);
+
+OCStackResult DeleteActionSets(OCResource** resource);
+
+OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actionsetName);
+
+OCStackResult GetActionSetFromString(OCResource **resource, unsigned char *request, char** method,
+        char **actionsetName);
+
+OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc);
+
+OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
+        OCClientResponse* clientResponse);
+
+void ActionSetCD(void *context);
+
+OCStackResult
+BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHandlerFlag flag*/,
+        OCResource *resource, OCEntityHandlerRequest *ehRequest);
+
+#endif // OIC_GROUP_H
index 085f497..8be0d12 100644 (file)
@@ -170,6 +170,7 @@ typedef enum {
     OC_STACK_MALFORMED_RESPONSE,        /* the remote reply contained malformed data */
     OC_STACK_PERSISTENT_BUFFER_REQUIRED,
     OC_STACK_INVALID_REQUEST_HANDLE,
+    OC_STACK_INVALID_DEVICE_INFO,
     OC_STACK_ERROR
     /* Error status code - END HERE */
 } OCStackResult;
@@ -276,6 +277,26 @@ typedef struct {
     OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
 }OCClientResponse;
 
+/**
+ * Following structure describes the device properties. All non-Null properties will be included
+ * in a device discovery request.
+ */
+typedef struct
+{
+    char *deviceName;
+    char *hostName;
+    char *deviceUUID;
+    char *contentType;
+    char *version;
+    char *manufacturerName;
+    char *manufacturerUrl;
+    char *modelNumber;
+    char *dateOfManufacture;
+    char *platformVersion;
+    char *firmwareVersion;
+    char *supportUrl;
+} OCDeviceInfo;
+
 typedef struct
 {
     // Request handle is passed to server via the entity handler for each incoming request.
@@ -404,7 +425,10 @@ OCStackResult OCProcess();
  * @param requiredUri        - URI of the resource to interact with
  * @param referenceUri       - URI of the reference resource
  * @param request            - JSON encoded request
- * @param qos                - quality of service
+ * @param qos                - quality of service. Note that if this API is called on a uri with
+ *                             the well-known multicast IP address, the qos will be forced to
+ *                             OC_LOW_QOS
+ *                             since it is impractical to send other QOS levels on such addresses.
  * @param clientApplicationCB- asynchronous callback function that is invoked
  *                             by the stack when discovery or resource interaction is complete
  * @param options            - The address of an array containing the vendor specific
@@ -490,6 +514,20 @@ OCStackResult OCStopPresence();
 OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler);
 
 /**
+ * Set device information.
+ *
+ * @param deviceInfo - Structure passed by the server application containing
+ *                     the device information.
+ *
+ *
+ * @return
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_INVALID_PARAM   - invalid paramerter
+ *     OC_STACK_ERROR           - stack process error
+ */
+OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo);
+
+/**
  * Create a resource.
  *
  * @param handle - pointer to handle to newly created resource.  Set by ocstack.  Used to refer to resource
index 650949c..9e14bd3 100644 (file)
 #define MAX_QUERY_LENGTH (64)
 
 /**
+ * Maximum length of the Manufacturer name supported by the server
+ * for manufacturer name
+ */
+#define MAX_MANUFACTURER_NAME_LENGTH (16)
+
+/**
+ * Maximum length of the URL to the Manufacturer details supported by
+ * the server.
+ */
+#define MAX_MANUFACTURER_URL_LENGTH (32)
+
+/**
  * Maximum number of resources which can be contained inside collection
  * resource.
  */
index 9f70f52..9965a22 100644 (file)
@@ -32,6 +32,8 @@
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
 static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
+static const char * TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core/d";
+static const char * TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY = "coap://224.0.1.187:5683/oc/core/d";
 static std::string putPayload = "{\"state\":\"on\",\"power\":5}";
 static std::string coapServerIP = "255.255.255.255";
 static std::string coapServerPort = "5683";
@@ -77,11 +79,17 @@ static void PrintUsage()
 
     #ifdef WITH_PRESENCE
     OC_LOG(INFO, TAG, "-t 12 :  Discover Resources and Initiate Nonconfirmable presence");
-    OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence with filter");
+    OC_LOG(INFO, TAG, "-t 13 :  Discover Resources and Initiate Nonconfirmable presence with "\
+            "filter");
+    OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable presence with "\
+            "2 filters");
     #endif
 
-    OC_LOG(INFO, TAG, "-t 14 :  Discover Resources and Initiate Nonconfirmable Observe Requests then cancel immediately");
-    OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable Get Request and add  vendor specific header options");
+    OC_LOG(INFO, TAG, "-t 15 :  Discover Resources and Initiate Nonconfirmable Observe Requests "\
+            "then cancel immediately");
+    OC_LOG(INFO, TAG, "-t 16 :  Discover Resources and Initiate Nonconfirmable Get Request and "\
+            "add  vendor specific header options");
+    OC_LOG(INFO, TAG, "-t 17 :  Discover Devices");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -324,12 +332,16 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             #ifdef WITH_PRESENCE
             case TEST_OBS_PRESENCE:
             case TEST_OBS_PRESENCE_WITH_FILTER:
+            case TEST_OBS_PRESENCE_WITH_FILTERS:
                 InitPresence();
                 break;
             #endif
             case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS:
                 InitGetRequest(OC_LOW_QOS, 1);
                 break;
+            case TEST_DISCOVER_DEV_REQ:
+                InitDeviceDiscovery();
+                break;
             default:
                 PrintUsage();
                 break;
@@ -339,17 +351,56 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ;
 
 }
+
+OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
+        OCClientResponse * clientResponse)
+{
+    if (ctx == (void*) DEFAULT_CONTEXT_VALUE)
+    {
+        OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully");
+    }
+
+    if(clientResponse)
+    {
+        //OC_LOG truncates the response as it is too long.
+        fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
+        fflush(stderr);
+    }
+
+    return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
+}
+
 #ifdef WITH_PRESENCE
 int InitPresence()
 {
+    OCStackResult result = OC_STACK_OK;
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
+    std::ostringstream querySuffix;
     query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI;
-    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER)
+    if(TEST_CASE == TEST_OBS_PRESENCE)
+    {
+        result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS,
+                presenceCB, NULL, 0);
+    }
+    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
     {
-        query << "?rt=core.light";
+        querySuffix.str("");
+        querySuffix << query.str() << "?rt=core.light";
+        result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
+                presenceCB, NULL, 0);
     }
-    return (InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, presenceCB, NULL, 0));
+    if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS)
+    {
+        if(result == OC_STACK_OK)
+        {
+            querySuffix.str("");
+            querySuffix << query.str() << "?rt=core.fan";
+            result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS,
+                    presenceCB, NULL, 0);
+        }
+    }
+    return result;
 }
 #endif
 int InitGetRequestToUnavailableResource()
@@ -495,6 +546,38 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
     }
 }
 
+int InitDeviceDiscovery()
+{
+    OCStackResult ret;
+    OCCallbackData cbData;
+    OCDoHandle handle;
+    char szQueryUri[64] = { 0 };
+
+    cbData.cb = DeviceDiscoveryReqCB;
+    cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
+    cbData.cd = NULL;
+
+    if(UNICAST_DISCOVERY)
+    {
+        strncpy(szQueryUri, TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY,
+                        (strlen(TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY) + 1));
+    }
+    else
+    {
+        strncpy(szQueryUri, TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY,
+                (strlen(TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY) + 1));
+    }
+
+    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+
+    if (ret != OC_STACK_OK)
+    {
+        OC_LOG(ERROR, TAG, "OCStack device error");
+    }
+
+    return ret;
+}
+
 int InitDiscovery()
 {
     OCStackResult ret;
index cb59cb0..96444ca 100644 (file)
@@ -55,9 +55,11 @@ typedef enum {
 #ifdef WITH_PRESENCE
     TEST_OBS_PRESENCE,
     TEST_OBS_PRESENCE_WITH_FILTER,
+    TEST_OBS_PRESENCE_WITH_FILTERS,
 #endif
     TEST_OBS_REQ_NON_CANCEL_IMM,
     TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS,
+    TEST_DISCOVER_DEV_REQ,
     MAX_TESTS
 } CLIENT_TEST;
 
@@ -91,6 +93,7 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
 int InitPostRequest(OCQualityOfService qos);
 int InitDeleteRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos);
+int InitDeviceDiscovery();
 int InitDiscovery();
 
 /* Function to retrieve ip address, port no. of the server
index 1bed2bf..6131cd0 100644 (file)
 
 #include <stdio.h>
 #include <string.h>
+#include <string>
 #include <stdlib.h>
 #include <unistd.h>
 #include <signal.h>
 #include <pthread.h>
+#include <array>
 #include "ocstack.h"
 #include "logger.h"
 #include "cJSON.h"
@@ -50,6 +52,7 @@ Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
 
 #ifdef WITH_PRESENCE
 static int stopPresenceCount = 10;
+#define numPresenceResources (2)
 #endif
 
 //TODO: Follow the pattern used in constructJsonResponse() when the payload is decided.
@@ -61,6 +64,20 @@ const char responsePayloadDeleteResourceNotSupported[] =
 
 
 char *gResourceUri= (char *)"/a/light";
+const char *contentType = "myContentType";
+const char *dateOfManufacture = "myDateOfManufacture";
+const char *deviceName = "myDeviceName";
+const char *deviceUUID = "myDeviceUUID";
+const char *firmwareVersion = "myFirmwareVersion";
+const char *hostName = "myHostName";
+const char *manufacturerName = "myManufacturerNa";
+const char *manufacturerUrl = "myManufacturerUrl";
+const char *modelNumber = "myModelNumber";
+const char *platformVersion = "myPlatformVersion";
+const char *supportUrl = "mySupportUrl";
+const char *version = "myVersion";
+
+OCDeviceInfo deviceInfo;
 
 static uint16_t OC_WELL_KNOWN_PORT = 5683;
 
@@ -466,6 +483,14 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
     return ehResult;
 }
 
+OCEntityHandlerResult
+OCNOPEntityHandlerCb (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *entityHandlerRequest)
+{
+    // This is callback is associated with the 2 presence notification
+    // resources. They are non-operational.
+    return OC_EH_OK;
+}
 
 OCEntityHandlerResult
 OCEntityHandlerCb (OCEntityHandlerFlag flag,
@@ -671,6 +696,57 @@ void *ChangeLightRepresentation (void *param)
     return NULL;
 }
 
+void *presenceNotificationGenerator(void *param)
+{
+    sleep(5);
+    (void)param;
+    OCDoHandle presenceNotificationHandles[numPresenceResources];
+    OCStackResult res = OC_STACK_OK;
+
+    std::array<std::string, numPresenceResources> presenceNotificationResources { {
+        std::string("core.fan"),
+        std::string("core.led") } };
+    std::array<std::string, numPresenceResources> presenceNotificationUris { {
+        std::string("/a/fan"),
+        std::string("/a/led") } };
+
+    for(int i=0; i<numPresenceResources; i++)
+    {
+        if(res == OC_STACK_OK)
+        {
+            sleep(1);
+            res = OCCreateResource(&presenceNotificationHandles[i],
+                    presenceNotificationResources.at(i).c_str(),
+                    "oc.mi.def",
+                    presenceNotificationUris.at(i).c_str(),
+                    OCNOPEntityHandlerCb,
+                    OC_DISCOVERABLE|OC_OBSERVABLE);
+        }
+        if(res != OC_STACK_OK)
+        {
+            OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to create resource "
+                    "%s with result %s.", presenceNotificationResources.at(i).c_str(),
+                    getResult(res));
+            break;
+        }
+    }
+    sleep(5);
+    for(int i=0; i<numPresenceResources; i++)
+    {
+        if(res == OC_STACK_OK)
+        {
+            res = OCDeleteResource(presenceNotificationHandles[i]);
+        }
+        if(res != OC_STACK_OK)
+        {
+            OC_LOG_V(ERROR, TAG, "\"Presence Notification Generator\" failed to delete "\
+                    "resource %s.", presenceNotificationResources.at(i).c_str());
+            break;
+        }
+    }
+    return NULL;
+}
+
 static void PrintUsage()
 {
     OC_LOG(INFO, TAG, "Usage : ocserver -o <0|1>");
@@ -685,6 +761,7 @@ int main(int argc, char* argv[])
     uint16_t port = OC_WELL_KNOWN_PORT;
     uint8_t ifname[] = "eth0";
     pthread_t threadId;
+    pthread_t threadId_presence;
     int opt;
 
     while ((opt = getopt(argc, argv, "o:")) != -1)
@@ -729,6 +806,24 @@ int main(int argc, char* argv[])
 
     OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb);
 
+    OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
+            deviceUUID, firmwareVersion, hostName, manufacturerName,
+            manufacturerUrl, modelNumber, platformVersion, supportUrl, version);
+
+    if (deviceResult != OC_STACK_OK)
+    {
+        OC_LOG(INFO, TAG, "Device Registration failed!");
+        exit (EXIT_FAILURE);
+    }
+
+    deviceResult = OCSetDeviceInfo(deviceInfo);
+
+    if (deviceResult != OC_STACK_OK)
+    {
+        OC_LOG(INFO, TAG, "Device Registration failed!");
+        exit (EXIT_FAILURE);
+    }
+
     /*
      * Declare and create the example resource: Light
      */
@@ -745,8 +840,15 @@ int main(int argc, char* argv[])
      */
     pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
 
+    /*
+     * Create a thread for generating changes that cause presence notifications
+     * to be sent to clients
+     */
+    pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL);
+
     // Break from loop with Ctrl-C
     OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    DeleteDeviceInfo();
     signal(SIGINT, handleSigInt);
     while (!gQuitFlag) {
         if (OCProcess() != OC_STACK_OK) {
@@ -762,6 +864,8 @@ int main(int argc, char* argv[])
      */
     pthread_cancel(threadId);
     pthread_join(threadId, NULL);
+    pthread_cancel(threadId_presence);
+    pthread_join(threadId_presence, NULL);
 
     OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
@@ -792,3 +896,126 @@ int createLightResource (char *uri, LightResource *lightResource)
 
     return 0;
 }
+
+void DeleteDeviceInfo()
+{
+    free(deviceInfo.contentType);
+    free(deviceInfo.dateOfManufacture);
+    free(deviceInfo.deviceName);
+    free(deviceInfo.deviceUUID);
+    free(deviceInfo.firmwareVersion);
+    free(deviceInfo.hostName);
+    free(deviceInfo.manufacturerName);
+    free(deviceInfo.manufacturerUrl);
+    free(deviceInfo.modelNumber);
+    free(deviceInfo.platformVersion);
+    free(deviceInfo.supportUrl);
+    free(deviceInfo.version);
+}
+
+bool DuplicateString(char** targetString, const char* sourceString)
+{
+    if(!sourceString)
+    {
+        return false;
+    }
+    else
+    {
+        *targetString = (char *) malloc(strlen(sourceString) + 1);
+
+        if(targetString)
+        {
+            strncpy(*targetString, sourceString, (strlen(sourceString) + 1));
+            return true;
+        }
+    }
+    return false;
+}
+
+OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
+        const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
+        const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
+        const char *modelNumber, const char *platformVersion, const char *supportUrl,
+        const char *version)
+{
+
+    bool success = true;
+
+    if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH))
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH))
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    if(!DuplicateString(&deviceInfo.contentType, contentType))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.deviceName, deviceName))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.hostName, hostName))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.modelNumber, modelNumber))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.platformVersion, platformVersion))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.supportUrl, supportUrl))
+    {
+        success = false;
+    }
+
+    if(!DuplicateString(&deviceInfo.version, version))
+    {
+        success = false;
+    }
+
+    if(success)
+    {
+        return OC_STACK_OK;
+    }
+
+    DeleteDeviceInfo();
+    return OC_STACK_ERROR;
+}
index f5e45e5..81a9507 100644 (file)
@@ -91,6 +91,15 @@ OCEntityHandlerResult ProcessNonExistingResourceRequest (OCEntityHandlerRequest
 void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest);
 void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest);
 
+void DeleteDeviceInfo();
+
+OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture,
+                const char *deviceName, const char *deviceUUID, const char *firmwareVersion,
+                const char *hostName, const char *manufacturerName, const char *manufacturerUrl,
+                const char *modelNumber, const char *platformVersion, const char *supportUrl,
+                const char *version);
+
+
 //-----------------------------------------------------------------------------
 // Callback functions
 //-----------------------------------------------------------------------------
index 2efba22..5d486bf 100644 (file)
 #include "debug.h"
 #include "cJSON.h"
 /// Module Name
+#include <stdio.h>
+
+#define WITH_GROUPACTION 1
+
+#include "oicgroup.h"
+
 #define TAG PCF("occollection")
 
 #define NUM_PARAM_IN_QUERY  2
@@ -141,6 +147,10 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
         {
             *ifParam = STACK_IF_BATCH;
         }
+        else if(strcmp (ifPtr, OC_RSRVD_INTERFACE_GROUP) == 0)
+        {
+            *ifParam = STACK_IF_GROUP;
+        }
         else
         {
             return OC_STACK_ERROR;
@@ -379,8 +389,10 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
     if (result != OC_STACK_OK)
         return result;
 
-    if ((ehRequest->method != OC_REST_GET) &&
-        (ehRequest->method != OC_REST_PUT))
+  
+    if(!((ehRequest->method == OC_REST_GET) || 
+        (ehRequest->method == OC_REST_PUT) ||
+        (ehRequest->method == OC_REST_POST)))
         return OC_STACK_ERROR;
 
     if (ehRequest->method == OC_REST_GET)
@@ -404,7 +416,9 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                 ((OCServerRequest *)ehRequest->requestHandle)->numResponses =
                         GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
                 return HandleBatchInterface(ehRequest);
-
+            case STACK_IF_GROUP:
+                return BuildCollectionGroupActionJSONResponse(OC_REST_GET/*flag*/,
+                        (OCResource *) ehRequest->resource, ehRequest);
             default:
                 return OC_STACK_ERROR;
         }
@@ -425,6 +439,29 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                         GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
                 return HandleBatchInterface(ehRequest);
 
+            case STACK_IF_GROUP:
+            {
+                OC_LOG_V(INFO, TAG, "IF_COLLECTION PUT with request ::\n%s\n ",
+                        ehRequest->reqJSONPayload);
+                return BuildCollectionGroupActionJSONResponse(OC_REST_PUT/*flag*/,
+                        (OCResource *) ehRequest->resource, ehRequest);
+            }
+            default:
+                return OC_STACK_ERROR;
+        }
+    }
+    else if (ehRequest->method == OC_REST_POST)
+    {
+
+        switch (ifQueryParam)
+        {
+            case STACK_IF_GROUP:
+            {
+                OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
+                        ehRequest->reqJSONPayload);
+                return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
+                        (OCResource *) ehRequest->resource, ehRequest);
+            }
             default:
                 return OC_STACK_ERROR;
         }
index a2a1c4e..f2267d1 100644 (file)
@@ -40,6 +40,7 @@
              TAG, PCF(#arg " is NULL")); return (retVal); } }
 
 extern OCResource *headResource;
+static cJSON *savedDeviceInfo = NULL;
 
 static const char * VIRTUAL_RSRCS[] = {
        "/oc/core",
@@ -71,7 +72,8 @@ static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
     if (!url)
         return OC_STACK_INVALID_URI;
 
-    if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0) {
+    if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0 ||
+                strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0) {
         *filterOn = STACK_RES_DISCOVERY_NOFILTER;
         if (query && *query) {
             char* strTokPtr;
@@ -85,6 +87,12 @@ static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
             } else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0) {
                 // Resource discovery with resource type filter
                 *filterOn = STACK_RES_DISCOVERY_RT_FILTER;
+            } else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0) {
+                //Device ID filter
+                *filterOn = STACK_DEVICE_DISCOVERY_DI_FILTER;
+            } else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0) {
+                //Device Name filter
+                *filterOn = STACK_DEVICE_DISCOVERY_DN_FILTER;
             } else {
                 // Other filter types not supported
                 return OC_STACK_INVALID_QUERY;
@@ -205,6 +213,85 @@ OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filt
     return ret;
 }
 
+OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filterValue,
+                                                    char *out, uint16_t *remaining)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+
+    if (savedDeviceInfo != NULL)
+    {
+        char *jsonStr = NULL;
+        uint16_t jsonLen = 0;
+        cJSON *repObj = cJSON_GetObjectItem(savedDeviceInfo, "rep");
+
+        OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponseForDevice"));
+
+        if (filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER)
+        {
+            if((cJSON_GetObjectItem(repObj,"di") != NULL) &&
+                    strcmp(cJSON_GetObjectItem(repObj,"di")->valuestring, filterValue) == 0)
+            {
+                ret = OC_STACK_OK;
+            }
+        }
+        else if (filterOn == STACK_DEVICE_DISCOVERY_DN_FILTER)
+        {
+            if((cJSON_GetObjectItem(repObj,"dn") != NULL) &&
+                    strcmp(cJSON_GetObjectItem(repObj,"dn")->valuestring, filterValue) == 0)
+            {
+                ret = OC_STACK_OK;
+            }
+        }
+        else if (filterOn == STACK_RES_DISCOVERY_NOFILTER)
+        {
+            ret = OC_STACK_OK;
+        }
+        else
+        {
+            ret = OC_STACK_INVALID_QUERY;
+        }
+
+        if (ret == OC_STACK_OK)
+        {
+            jsonStr = cJSON_PrintUnformatted (savedDeviceInfo);
+
+            if(jsonStr)
+            {
+                jsonLen = strlen(jsonStr);
+
+                if (jsonLen < *remaining)
+                {
+                    strncpy(out, jsonStr, (jsonLen + 1));
+                    *remaining = *remaining - jsonLen;
+                    ret = OC_STACK_OK;
+                }
+                else
+                {
+                    ret = OC_STACK_ERROR;
+                }
+
+                free(jsonStr);
+            }
+            else
+            {
+                ret = OC_STACK_ERROR;
+            }
+        }
+        else
+        {
+            ret = OC_STACK_INVALID_DEVICE_INFO;
+        }
+    }
+    else
+    {
+        //error so that stack won't respond with empty payload
+        ret = OC_STACK_INVALID_DEVICE_INFO;
+    }
+
+    OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponseForDevice"));
+    return ret;
+}
+
 TODO ("Does it make sense to make this method as inline")
 const char * GetVirtualResourceUri( OCVirtualResources resource)
 {
@@ -429,6 +516,33 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
                 result = OCDoResponse(&response);
             }
         }
+        else if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_DEVICE_URI)) == 0)
+        {
+            remaining = MAX_RESPONSE_LENGTH;
+            ptr = discoveryResBuf;
+
+            result = BuildVirtualResourceResponseForDevice(filterOn, filterValue,
+                    (char*)ptr, &remaining);
+
+            if(result == OC_STACK_OK)
+            {
+                ptr += strlen((char*)ptr);
+            }
+
+            if(remaining < MAX_RESPONSE_LENGTH)
+            {
+                OCEntityHandlerResponse response = {0};
+
+                response.ehResult = OC_EH_OK;
+                response.payload = discoveryResBuf;
+                response.payloadSize = strlen((const char *)discoveryResBuf) + 1;
+                response.persistentBufferFlag = 0;
+                response.requestHandle = (OCRequestHandle) request;
+                response.resourceHandle = (OCResourceHandle) resource;
+
+                result = OCDoResponse(&response);
+            }
+        }
         #ifdef WITH_PRESENCE
         else
         {
@@ -644,4 +758,109 @@ ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerReque
     return ret;
 }
 
+void DeleteDeviceInfo()
+{
+    if(savedDeviceInfo)
+    {
+        cJSON_Delete(savedDeviceInfo);
+    }
+}
+
+OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
+{
+    DeleteDeviceInfo();
+
+    savedDeviceInfo = cJSON_CreateObject();
+    cJSON *repObj = NULL;
+
+    cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_HREF,
+            cJSON_CreateString(GetVirtualResourceUri(OC_DEVICE_URI)));
+
+    cJSON_AddItemToObject (savedDeviceInfo, "rep", repObj = cJSON_CreateObject());
+
+    if (deviceInfo.contentType)
+    {
+        cJSON_AddItemToObject (repObj, "ct",
+                cJSON_CreateString(deviceInfo.contentType));
+    }
+
+    if (deviceInfo.dateOfManufacture)
+    {
+        cJSON_AddItemToObject (repObj, "mndt",
+                cJSON_CreateString(deviceInfo.dateOfManufacture));
+    }
+
+    if (deviceInfo.deviceName)
+    {
+        cJSON_AddItemToObject (repObj, "dn",
+                cJSON_CreateString(deviceInfo.deviceName));
+    }
+
+    if (deviceInfo.deviceUUID)
+    {
+        cJSON_AddItemToObject (repObj, "di",
+                cJSON_CreateString(deviceInfo.deviceUUID));
+    }
+
+    if (deviceInfo.firmwareVersion)
+    {
+        cJSON_AddItemToObject (repObj, "mnfv",
+                cJSON_CreateString(deviceInfo.firmwareVersion));
+    }
+
+    if (deviceInfo.hostName)
+    {
+        cJSON_AddItemToObject (repObj, "hn", cJSON_CreateString(deviceInfo.hostName));
+    }
+
+    if (deviceInfo.manufacturerName)
+    {
+        if(strlen(deviceInfo.manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        cJSON_AddItemToObject (repObj, "mnmn",
+                cJSON_CreateString(deviceInfo.manufacturerName));
+    }
+
+    if (deviceInfo.manufacturerUrl)
+    {
+        if(strlen(deviceInfo.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)
+        {
+            DeleteDeviceInfo();
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        cJSON_AddItemToObject (repObj, "mnml",
+                cJSON_CreateString(deviceInfo.manufacturerUrl));
+    }
+
+    if (deviceInfo.modelNumber)
+    {
+        cJSON_AddItemToObject (repObj, "mnmo",
+                cJSON_CreateString(deviceInfo.modelNumber));
+    }
+
+    if (deviceInfo.platformVersion)
+    {
+        cJSON_AddItemToObject (repObj, "mnpv",
+                cJSON_CreateString(deviceInfo.platformVersion));
+    }
+
+    if (deviceInfo.supportUrl)
+    {
+        cJSON_AddItemToObject (repObj, "mnsl",
+                cJSON_CreateString(deviceInfo.supportUrl));
+    }
+
+    if (deviceInfo.version)
+    {
+        cJSON_AddItemToObject (repObj, "icv",
+                cJSON_CreateString(deviceInfo.version));
+    }
+
+    return OC_STACK_OK;
+}
 
index fd4c754..b2aec91 100644 (file)
@@ -457,6 +457,7 @@ OCStackResult OCStop()
 
     // Free memory dynamically allocated for resources
     deleteAllResources();
+    DeleteDeviceInfo();
 
     // Make call to OCCoAP layer
     if (OCStopCoAP() == OC_STACK_OK)
@@ -913,6 +914,18 @@ OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandle
     return OC_STACK_OK;
 }
 
+OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
+{
+    OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
+
+    if(myStackMode == OC_CLIENT)
+    {
+        return OC_STACK_ERROR;
+    }
+
+    return SaveDeviceInfo(deviceInfo);
+}
+
 /**
  * Create a resource
  *
diff --git a/resource/csdk/stack/src/oicgroup.c b/resource/csdk/stack/src/oicgroup.c
new file mode 100644 (file)
index 0000000..b9f70ac
--- /dev/null
@@ -0,0 +1,864 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#define _POSIX_C_SOURCE 200112L
+#include <string.h>
+
+#include "cJSON.h"
+#include "ocmalloc.h"
+#include "oicgroup.h"
+#include "ocresource.h"
+#include "occollection.h"
+
+#define TAG PCF("OICGROUP")
+
+#define DESC_DELIMITER "\""
+#define ACTION_DELIMITER "*"
+#define ATTR_DELIMITER "|"
+
+typedef struct aggregatehandleinfo
+{
+    OCServerRequest *ehRequest;
+    OCDoHandle required;
+    OCResource *collResource;
+
+    struct aggregatehandleinfo *next;
+} ClientRequstInfo;
+
+// unsigned int nHandleIdx = 0;
+// ClientRequstInfo g_AggregateResponseHandle[10];
+
+ClientRequstInfo *clientRequstList = NULL;
+
+void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
+{
+    ClientRequstInfo *tmp = NULL;
+
+    if (*head != NULL)
+    {
+        tmp = *head;
+
+        while (tmp->next)
+        {
+            tmp = tmp->next;
+        }
+        tmp->next = add;
+    }
+    else
+    {
+        *head = add;
+    }
+}
+
+ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle)
+{
+    ClientRequstInfo *tmp = NULL;
+
+    tmp = head;
+
+    if (tmp)
+    {
+        while (tmp)
+        {
+//            printf("%p :: %p\n", tmp->required, handle);
+            if (tmp->required == handle)
+            {
+                break;
+            }
+
+            tmp = tmp->next;
+        }
+
+        return tmp;
+    }
+    return NULL;
+}
+
+void RemoveClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* del)
+{
+    ClientRequstInfo *tmp = NULL;
+
+    if (*head == del)
+    {
+        *head = (*head)->next;
+    }
+    else
+    {
+        tmp = *head;
+        while (tmp->next && (tmp->next != del))
+        {
+            tmp = tmp->next;
+        }
+        if (tmp->next)
+        {
+            tmp->next = del->next;
+        }
+    }
+}
+
+
+
+void AddCapability(OCCapability** head, OCCapability* node)
+{
+    OCCapability *pointer = *head;
+    if (NULL == pointer)
+    {
+        *head = node;
+    }
+    else
+    {
+        while (pointer->next != NULL)
+        {
+            pointer = pointer->next;
+        }
+
+        pointer->next = node;
+    }
+}
+
+void AddAction(OCAction** head, OCAction* node)
+{
+    OCAction *pointer = *head;
+    if (NULL == pointer)
+    {
+        *head = node;
+    }
+    else
+    {
+
+        while (pointer->next != NULL)
+        {
+            pointer = pointer->next;
+        }
+
+        pointer->next = node;
+    }
+}
+
+void AddActionSet(OCActionSet **head, OCActionSet* node)
+{
+    OCActionSet *pointer = *head;
+    if (NULL == pointer)
+    {
+        *head = node;
+    }
+    else
+    {
+
+        while (pointer->next != NULL)
+        {
+            pointer = pointer->next;
+        }
+
+        pointer->next = node;
+    }
+}
+
+void DeleteCapability(OCCapability *del)
+{
+    free(del->capability);
+    del->capability = NULL;
+    free(del->status);
+    del->status = NULL;
+}
+
+void DeleteAction(OCAction** action)
+{
+    OCCapability* pointer = (*action)->head;
+    OCCapability* pDel = NULL;
+
+    while (pointer)
+    {
+        pDel = pointer;
+        pointer = pointer->next;
+
+        DeleteCapability(pDel);
+        pDel->next = NULL;
+    }
+    OCFree((*action)->resourceUri);
+    (*action)->resourceUri = NULL;
+    (*action)->next = NULL;
+}
+
+void DeleteActionSet(OCActionSet** actionset)
+{
+    OCAction* pointer = (*actionset)->head;
+    OCAction* pDel = NULL;
+
+    while (pointer)
+    {
+        pDel = pointer;
+        pointer = pointer->next;
+
+        DeleteAction(&pDel);
+        pDel->next = NULL;
+    }
+
+    OCFree((*actionset)->actionsetName);
+    (*actionset)->head = NULL;
+}
+
+OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actionsetName)
+{
+
+    if (*resource != NULL)
+    {
+
+        OCActionSet *pointer = NULL;
+        OCActionSet *pDel = NULL;
+
+        pointer = (*resource)->actionsetHead;
+
+        if (pointer == NULL)
+        {
+            return OC_STACK_ERROR;
+        }
+        else
+        {
+            if (strcmp(pointer->actionsetName, actionsetName) == 0)
+            {
+                if (pointer->next != NULL)
+                    (*resource)->actionsetHead = pointer->next;
+                else
+                    (*resource)->actionsetHead = NULL;
+
+                DeleteActionSet(&pointer);
+
+            }
+            else if (pointer->next != NULL)
+            {
+                while (pointer)
+                {
+                    if (pointer->next != NULL)
+                    {
+                        if (strcmp(pointer->next->actionsetName, actionsetName) == 0)
+                        {
+                            pDel = pointer->next;
+                            pointer->next = pointer->next->next;
+
+                            DeleteActionSet(&pDel);
+                        }
+                    }
+                }
+            }
+
+            return OC_STACK_OK;
+        }
+
+    }
+
+    return OC_STACK_ERROR;
+}
+
+OCStackResult DeleteActionSets(OCResource** resource)
+{
+    OCActionSet *pointer = (*resource)->actionsetHead;
+    OCActionSet *pDel = pointer;
+
+    while (pointer)
+    {
+        pDel = pointer;
+        pointer = pointer->next;
+
+        DeleteActionSet(&pDel);
+        pDel->next = NULL;
+    }
+
+    (*resource)->actionsetHead = NULL;
+    return OC_STACK_OK;
+}
+
+OCStackResult GetActionSet(const char *actionName, OCActionSet *head, OCActionSet** actionset)
+{
+    OCActionSet *pointer = head;
+
+    while (pointer)
+    {
+        if (strcmp(pointer->actionsetName, actionName) == 0)
+        {
+            *actionset = pointer;
+            return OC_STACK_OK;
+        }
+
+        pointer = pointer->next;
+    }
+
+    return OC_STACK_ERROR;
+
+}
+
+OCStackResult GetActionSetFromString(OCResource **resource, unsigned char *request, char** method,
+        char **actionsetName)
+{
+    char *acitonRequest;
+    char *iterTokenPtr = NULL;
+    char *iterToken = NULL;
+    char *description = NULL;
+    char *iterDescPtr = NULL;
+
+    char *attributes = NULL;
+    char *iterAttrbutesPtr = NULL;
+
+    char *attr = NULL;
+    char *iterAttrPtr = NULL;
+
+    OCActionSet* actionset = NULL;
+    OCAction* action = NULL;
+
+    acitonRequest = (char *) OCMalloc(strlen((char *) request) + 1);
+    strncpy(acitonRequest, (char *) request, strlen((char *) request) + 1);
+
+    //printf("\t%s\n", acitonRequest);
+    if (acitonRequest != NULL)
+    {
+        iterToken = (char *) strtok_r(acitonRequest, DESC_DELIMITER, &iterTokenPtr);
+
+        while (iterToken != NULL)
+        {
+            if (strcmp(iterToken, "ActionSet") == 0)
+            { // if iterToken is ActionSet, will be created and added a new action set.
+
+                *method = (char *) OCMalloc(strlen(iterToken) + 1);
+                strncpy(*method, iterToken, strlen(iterToken) + 1);
+
+                //GetActionName(iterToken, &actionsetName);
+                // printf("%s\n", iterToken, &iterTokenPtr);
+                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is mean ':'.
+                // printf("%s\n", iterToken);
+                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is body of action description.
+                // printf("%s\n", iterToken);
+
+                // printf("DESC :: %s\n", iterToken);
+                description = (char *) OCMalloc(strlen(iterToken) + 1);
+                strncpy(description, iterToken, strlen(iterToken) + 1);
+                // printf("DESC Copied :: %s\n", description);
+
+                // Find the action name from description.
+                iterDescPtr = NULL;
+                iterToken = (char *) strtok_r(description, ACTION_DELIMITER, &iterDescPtr);
+                //while(iterToken != NULL)
+                if (iterToken != NULL)
+                {
+                    if (*actionsetName != NULL)
+                    {
+                        // printf("ERROR :: ACTIONSET NAME as ActionSet(%s)\n", iterToken);
+                        return OC_STACK_ERROR; // ERROR OCCURED.
+                    }
+                    else
+                    {
+                        //  Actionset name.
+                        // printf("ACTION SET NAME :: %s\n", iterToken);
+                        *actionsetName = (char *) OCMalloc(strlen(iterToken) + 1);
+
+                        strncpy(*actionsetName, iterToken, strlen(iterToken) + 1);
+                        // printf("ACTION SET NAME :: %s\n", *actionsetName);
+                        // break;
+                    }
+
+                    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr);
+                }
+                else
+                {
+                    return OC_STACK_ERROR;
+
+                } // end Action Set Name.
+
+                // New ActionSet Add to OCResource's ActionSet list.
+                // 1. Allocate a new pointer for actionset.
+                actionset = (OCActionSet*) OCMalloc(sizeof(OCActionSet));
+                // 2. Initiate actionset.
+                memset(actionset, 0, sizeof(OCActionSet));
+                actionset->actionsetName = (char *) OCMalloc(strlen(*actionsetName) + 1);
+                strncpy(actionset->actionsetName, *actionsetName, strlen(*actionsetName) + 1);
+                // printf("ACTION SET NAME :: %s\n", actionset->actionsetName);
+
+                while (iterToken != NULL)
+                {
+                    action = (OCAction *) OCMalloc(sizeof(OCAction));
+                    memset(action, 0, sizeof(OCAction));
+
+                    // printf("ATTR Copied :: %s\n", iterToken);
+                    attributes = (char *) OCMalloc(strlen(iterToken) + 1);
+                    strncpy(attributes, iterToken, strlen(iterToken) + 1);
+                    // printf("ATTR Copied :: %s\n", attributes);
+
+                    iterToken = (char *) strtok_r(attributes, ATTR_DELIMITER, &iterAttrbutesPtr);
+                    while (iterToken != NULL)
+                    {
+                        attr = (char *) OCMalloc(strlen(iterToken) + 1);
+                        strncpy(attr, iterToken, strlen(iterToken) + 1);
+
+                        iterToken = (char *) strtok_r(attr, "=", &iterAttrPtr);
+                        while (iterToken != NULL)
+                        {
+                            // Find the URI from description.
+                            if (strcmp(iterToken, "uri") == 0)
+                            {
+                                iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr);
+                                //printf("uri :: %s\n", iterToken);
+                                action->resourceUri = (char *) OCMalloc(strlen(iterToken) + 1);
+                                strncpy(action->resourceUri, iterToken, strlen(iterToken) + 1);
+                            }
+                            else
+                            {
+                                OCCapability* capa = (OCCapability*) OCMalloc(sizeof(OCCapability));
+                                memset(capa, 0, sizeof(OCCapability));
+                                //printf("%s :: ", iterToken);
+                                capa->capability = (char *) OCMalloc(strlen(iterToken) + 1);
+                                strncpy(capa->capability, iterToken, strlen(iterToken) + 1);
+                                iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr);
+                                //printf("%s\n", iterToken);
+                                capa->status = (char *) OCMalloc(strlen(iterToken) + 1);
+                                strncpy(capa->status, iterToken, strlen(iterToken) + 1);
+
+                                AddCapability(&action->head, capa);
+                            }
+
+                            iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr);
+                        }
+
+                        iterToken = (char *) strtok_r(NULL, ATTR_DELIMITER, &iterAttrbutesPtr);
+                    } // End of Action
+
+                    AddAction(&actionset->head, action);
+
+                    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr);
+                }
+
+                // 3. Add the pointer OCResource's ActionSet list.
+                AddActionSet(&(*resource)->actionsetHead, actionset);
+                return OC_STACK_OK;
+            }
+            else if (strcmp(iterToken, "DoAction") == 0 || strcmp(iterToken, "DelActionSet") == 0
+                    || strcmp(iterToken, "GetActionSet") == 0)
+            {
+                *method = (char *) OCMalloc(strlen(iterToken) + 1);
+                strncpy(*method, iterToken, strlen(iterToken) + 1);
+
+                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is mean ':'.
+                // printf("%s\n", iterToken);
+                iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is body of action description.
+                // printf("%s\n", iterToken);
+
+                description = (char *) OCMalloc(strlen(iterToken) + 1);
+                strncpy(description, iterToken, strlen(iterToken) + 1);
+
+                // Find the action name from description.
+                iterDescPtr = NULL;
+                iterToken = (char *) strtok_r(description, ACTION_DELIMITER, &iterDescPtr);
+                if (iterToken != NULL)
+                {
+                    if (*actionsetName != NULL)
+                    {
+                        // printf("ERROR :: ACTIONSET NAME as ActionSet(%s)\n", iterToken);
+                        return OC_STACK_ERROR; // ERROR OCCURED.
+                    }
+                    else
+                    {
+                        //  Actionset name.
+                        // printf("ACTION SET NAME :: %s\n", iterToken);
+                        *actionsetName = (char *) OCMalloc(strlen(iterToken) + 1);
+
+                        strncpy(*actionsetName, iterToken, strlen(iterToken) + 1);
+                        // printf("ACTION SET NAME :: %s\n", *actionsetName);
+                    }
+
+                    iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr);
+                    return OC_STACK_OK;
+                }
+                else
+                {
+                    return OC_STACK_ERROR;
+
+                } // end Action Set Name.
+                break;
+            }
+
+            iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr);
+        }
+    }
+
+    return OC_STACK_ERROR;
+}
+
+OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc)
+{
+    char temp[1024] =
+    { 0 };
+    int remaining = 1023;
+
+    // OCActionSet *as = resource->actionsetHead;
+    // while(as != NULL)
+    // {
+    printf("\n\n\nAction Set Name :: %s\n", actionset->actionsetName);
+    OCAction *action = actionset->head;
+
+    if (remaining >= strlen(actionset->actionsetName) + 1)
+    {
+        strcat(temp, actionset->actionsetName);
+        remaining -= strlen(actionset->actionsetName);
+        strcat(temp, "*");
+        remaining--;
+    }
+    else
+    {
+        return OC_STACK_ERROR;
+    }
+
+    while (action != NULL)
+    {
+        printf("\tURI :: %s\n", action->resourceUri);
+        strcat(temp, "uri=");
+        remaining -= strlen("uri=");
+        strcat(temp, action->resourceUri);
+        remaining -= strlen(action->resourceUri);
+        strcat(temp, "|");
+        remaining--;
+
+        OCCapability *capas = action->head;
+        while (capas != NULL)
+        {
+            printf("\t\t%s = %s\n", capas->capability, capas->status);
+            strcat(temp, capas->capability);
+            remaining -= strlen(capas->capability);
+            strcat(temp, "=");
+            remaining--;
+            strcat(temp, capas->status);
+            remaining -= strlen(capas->capability);
+
+            capas = capas->next;
+            if (capas != NULL)
+            {
+                strcat(temp, "|");
+            }
+        }
+
+        action = action->next;
+        if (action != NULL)
+        {
+            strcat(temp, "*");
+            remaining--;
+        }
+    }
+    //     as = as->next;
+    // }
+
+    *desc = (char *) OCMalloc(1024 - remaining);
+    strcpy(*desc, temp);
+    // printf("\t\tPlain Text = %s(%i)\n", *desc, 1024 - remaining);
+
+    return OC_STACK_OK;
+}
+
+OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
+        OCClientResponse* clientResponse)
+{
+    printf("\n\n\tcallback is called\n\n");
+
+    ClientRequstInfo *info = GetClientRequestInfo(clientRequstList, handle);
+
+    if (info)
+    {
+        int idx;
+
+        unsigned char *responseJson;
+        responseJson = (unsigned char *) OCMalloc(
+                (unsigned int) (strlen((char *) clientResponse->resJSONPayload) + 1));
+
+        // We need the body of response.
+        // Copy the body from the response
+        strcpy((char *) responseJson, ((char *) clientResponse->resJSONPayload
+                + OC_JSON_PREFIX_LEN));
+        idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
+        // And insert NULL at the end of body.
+        (responseJson[idx]) = 0;
+
+        OCEntityHandlerResponse response = { 0 };
+        response.ehResult = OC_EH_OK;
+        response.payload = responseJson;
+        response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
+        response.persistentBufferFlag = 0;
+        response.requestHandle = (OCRequestHandle) info->ehRequest;
+        response.resourceHandle = (OCResourceHandle) info->collResource;
+
+        OCDoResponse(&response);
+
+        RemoveClientRequestInfo(&clientRequstList, info);
+        OCFree(responseJson);
+    }
+
+    // g_AggregateResponseHandle
+
+    return OC_STACK_KEEP_TRANSACTION;
+}
+
+void ActionSetCD(void *context)
+{
+    // printf("\n\t\tCD is called\n");
+
+    // free( context );
+}
+
+OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16_t *remaining)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *json;
+    cJSON *body;
+
+    char *jsonStr;
+    uint16_t jsonLen;
+
+    OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
+    json = cJSON_CreateObject();
+
+    cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
+
+    OCCapability* pointerCapa = action->head;
+    while (pointerCapa)
+    {
+        cJSON_AddStringToObject(body, pointerCapa->capability, pointerCapa->status);
+        pointerCapa = pointerCapa->next;
+    }
+
+    jsonStr = cJSON_PrintUnformatted(json);
+
+    jsonLen = strlen(jsonStr);
+    if (jsonLen < *remaining)
+    {
+        strcat((char*) bufferPtr, jsonStr);
+        *remaining -= jsonLen;
+        bufferPtr += jsonLen;
+        ret = OC_STACK_OK;
+    }
+
+    cJSON_Delete(json);
+    free(jsonStr);
+
+    return ret;
+}
+
+unsigned int GetNumOfTargetResource(OCAction *actionset)
+{
+    int numOfREsource = 0;
+
+    OCAction *pointerAction = actionset;
+
+    while (pointerAction != NULL)
+    {
+        numOfREsource++;
+        pointerAction = pointerAction->next;
+    }
+
+    return numOfREsource;
+}
+
+OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const unsigned char *action)
+{
+    OCCallbackData cbdata =
+    { 0 };
+    cbdata.cb = &ActionSetCB;
+    cbdata.cd = &ActionSetCD;
+    cbdata.context = (void *) 0x99;
+
+    return OCDoResource(handle, OC_REST_PUT, targetUri,
+    //temp->rsrcType->resourcetypename,
+            NULL, (char *) action, OC_NA_QOS, &cbdata, NULL, 0);
+}
+
+OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHandlerFlag flag*/,
+        OCResource *resource, OCEntityHandlerRequest *ehRequest)
+{
+    OCStackResult stackRet = OC_STACK_ERROR;
+
+    OC_LOG(INFO, TAG, PCF("Group Action is requested."));
+    // if (stackRet == OC_STACK_OK)
+    {
+
+        char *doWhat = NULL;
+        char *actionName = NULL;
+
+        size_t bufferLength = 0;
+        unsigned char buffer[MAX_RESPONSE_LENGTH] =
+        { 0 };
+        unsigned char *bufferPtr = NULL;
+
+        bufferPtr = buffer;
+
+        OCResource * collResource = (OCResource *) ehRequest->resource;
+
+        char *jsonResponse;
+
+        cJSON *json;
+        cJSON *format;
+
+        if (method == OC_REST_PUT)
+        {
+            json = cJSON_CreateObject();
+            cJSON_AddStringToObject(json, "href", resource->uri);
+            cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
+
+            OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
+
+            unsigned char *actionPtr = (unsigned char *) ehRequest->reqJSONPayload;
+            GetActionSetFromString(&resource, actionPtr, &doWhat, &actionName);
+
+            if (strcmp(doWhat, "DelActionSet") == 0)
+            {
+                if (FindAndDeleteActionSet(&resource, actionName) == OC_STACK_OK)
+                {
+                    stackRet = OC_STACK_OK;
+                }
+                else
+                {
+                    stackRet = OC_STACK_ERROR;
+                }
+            }
+
+            jsonResponse = cJSON_Print(json);
+            cJSON_Delete(json);
+
+            strcat((char *) bufferPtr, jsonResponse);
+
+            bufferLength = strlen((const char *) buffer);
+            if (bufferLength > 0)
+            {
+                OCEntityHandlerResponse response =
+                { 0 };
+                response.ehResult = OC_EH_OK;
+                response.payload = buffer;
+                response.payloadSize = bufferLength + 1;
+                response.persistentBufferFlag = 0;
+                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+                response.resourceHandle = (OCResourceHandle) collResource;
+                stackRet = OCDoResponse(&response);
+            }
+
+            stackRet = OC_STACK_OK;
+        }
+
+        if (method == OC_REST_POST)
+        {
+            OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
+
+            OCActionSet *actionset = NULL;
+            unsigned char *actionPtr = (unsigned char *) ehRequest->reqJSONPayload;
+
+            GetActionSetFromString(&resource, actionPtr, &doWhat, &actionName);
+
+            json = cJSON_CreateObject();
+            cJSON_AddStringToObject(json, "href", resource->uri);
+
+            if (strcmp(doWhat, "DoAction") == 0)
+            {
+                if (GetActionSet(actionName, resource->actionsetHead, &actionset) != OC_STACK_OK)
+                {
+                    OC_LOG(INFO, TAG, PCF("ERROR"));
+                    stackRet = OC_STACK_ERROR;
+                }
+
+                if (actionset == NULL)
+                {
+                    OC_LOG(INFO, TAG, PCF("ERROR"));
+                    stackRet = OC_STACK_ERROR;
+                }
+                else
+                {
+
+                    OCAction *pointerAction = actionset->head;
+
+                    unsigned int num = GetNumOfTargetResource(pointerAction);
+
+                    ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
+                            HandleAggregateResponse;
+                    ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
+
+//                    printf("ActionSet Name :: %s\n", actionset->actionsetName);
+                    while (pointerAction != NULL)
+                    {
+                        unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
+                        unsigned char* actionDescPtr = actionDesc;
+                        uint16_t remaining = MAX_RESPONSE_LENGTH;
+
+                        strcpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX);
+                        BuildActionJSON(pointerAction, actionDescPtr, &remaining);
+                        strcat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX);
+
+                        ClientRequstInfo *info = (ClientRequstInfo *) OCMalloc(
+                                sizeof(ClientRequstInfo));
+                        memset(info, 0, sizeof(ClientRequstInfo));
+
+                        info->collResource = resource;
+                        info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
+
+                        SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
+
+                        AddClientRequestInfo(&clientRequstList, info);
+
+
+                        pointerAction = pointerAction->next;
+                    }
+
+
+                    stackRet = OC_STACK_OK;
+                }
+            }
+            else if (strcmp(doWhat, "GetActionSet") == 0)
+            {
+                char *plainText = NULL;
+                OCActionSet *actionset = NULL;
+
+                cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
+                GetActionSet(actionName, resource->actionsetHead, &actionset);
+                if (actionset != NULL)
+                {
+                    GetStringFromActionSet(actionset, &plainText);
+
+                    if (plainText != NULL)
+                    {
+                        cJSON_AddStringToObject(format, "ActionSet", plainText);
+                    }
+
+                    stackRet = OC_STACK_OK;
+                }
+            }
+
+            jsonResponse = cJSON_Print(json);
+            cJSON_Delete(json);
+
+            strcat((char *) bufferPtr, jsonResponse);
+
+            bufferLength = strlen((const char *) buffer);
+            if (bufferLength > 0)
+            {
+                OCEntityHandlerResponse response =
+                { 0 };
+                response.ehResult = OC_EH_OK;
+                response.payload = buffer;
+                response.payloadSize = bufferLength + 1;
+                response.persistentBufferFlag = 0;
+                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+                response.resourceHandle = (OCResourceHandle) collResource;
+                stackRet = OCDoResponse(&response);
+            }
+        }
+    }
+
+    return stackRet;
+}
index 12a7dcc..4a12d01 100644 (file)
@@ -60,11 +60,13 @@ roomserver = examples_env.Program('roomserver', 'roomserver.cpp')
 roomclient = examples_env.Program('roomclient', 'roomclient.cpp')
 garageserver = examples_env.Program('garageserver', 'garageserver.cpp')
 garageclient = examples_env.Program('garageclient', 'garageclient.cpp')
+devicediscoveryserver = examples_env.Program('devicediscoveryserver', 'devicediscoveryserver.cpp')
+devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicediscoveryclient.cpp')
 
 Alias("examples", [simpleserver, simpleserverHQ, simpleclient, simpleclientHQ,
                fridgeserver, fridgeclient, presenceserver, presenceclient,
                simpleclientserver, roomserver, roomclient, garageserver,
-               garageclient])
+               garageclient, devicediscoveryserver, devicediscoveryclient])
 env.AppendTarget('examples')
 
 #ios doesn't allow run application from terminal, so won't build these examples
diff --git a/resource/examples/devicediscoveryclient.cpp b/resource/examples/devicediscoveryclient.cpp
new file mode 100644 (file)
index 0000000..f08a8c7
--- /dev/null
@@ -0,0 +1,147 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+///This sample demonstrates the device discovery feature
+///The client queries for the device related information
+///stored by the server.
+///
+
+#include <mutex>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+
+//Callback after device information is received
+void receivedDeviceInfo(const OCRepresentation& rep)
+{
+    std::cout << "\nDevice Information received ---->\n";
+
+    std::string contentType;
+    std::string dateOfManufacture;
+    std::string deviceName;
+    std::string deviceUUID;
+    std::string firmwareVersion;
+    std::string hostName;
+    std::string manufacturerName;
+    std::string manufacturerUrl;
+    std::string modelNumber;
+    std::string platformVersion;
+    std::string supportUrl;
+    std::string version;
+
+    if(rep.getValue("ct", contentType))
+    {
+        std::cout << "Content Type: " << contentType << std::endl;
+    }
+
+    if(rep.getValue("mndt", dateOfManufacture))
+    {
+        std::cout << "Date of manufacture: " << dateOfManufacture << std::endl;
+    }
+
+    if(rep.getValue("dn", deviceName))
+    {
+        std::cout << "Device Name: " << deviceName << std::endl;
+    }
+
+    if(rep.getValue("di", deviceUUID))
+    {
+        std::cout << "Device UUID: " << deviceUUID << std::endl;
+    }
+
+    if(rep.getValue("mnfv", firmwareVersion))
+    {
+        std::cout << "Firmware Version: " << firmwareVersion << std::endl;
+    }
+
+    if(rep.getValue("hn", hostName))
+    {
+        std::cout << "Host Name: " << hostName << std::endl;
+    }
+
+    if(rep.getValue("mnmn", manufacturerName))
+    {
+        std::cout << "Manufacturer Name: " << manufacturerName << std::endl;
+    }
+
+    if(rep.getValue("mnml", manufacturerUrl))
+    {
+        std::cout << "Manufacturer Url: " << manufacturerUrl << std::endl;
+    }
+
+    if(rep.getValue("mnmo", modelNumber))
+    {
+        std::cout << "Model No. : " << modelNumber << std::endl;
+    }
+
+    if(rep.getValue("mnpv", platformVersion))
+    {
+        std::cout << "Platform Version: " << platformVersion << std::endl;
+    }
+
+    if(rep.getValue("mnsl", supportUrl))
+    {
+        std::cout << "Support URL: " << supportUrl << std::endl;
+    }
+
+    if(rep.getValue("icv", version))
+    {
+        std::cout << "Version: " << version << std::endl;
+    }
+}
+
+int main() {
+
+    // Create PlatformConfig object
+    PlatformConfig cfg {
+        OC::ServiceType::InProc,
+        OC::ModeType::Client,
+        "0.0.0.0",
+        0,
+        OC::QualityOfService::LowQos
+    };
+
+    OCPlatform::Configure(cfg);
+    try
+    {
+        OCPlatform::getDeviceInfo("", "coap://224.0.1.187/oc/core/d", &receivedDeviceInfo);
+        std::cout<< "Querying for device information... " <<std::endl;
+
+        // A condition variable will free the mutex it is given, then do a non-
+        // intensive block until 'notify' is called on it.  In this case, since we
+        // don't ever call cv.notify, this should be a non-processor intensive version
+        // of while(true);
+        std::mutex blocker;
+        std::condition_variable cv;
+        std::unique_lock<std::mutex> lock(blocker);
+        cv.wait(lock);
+
+    }catch(OCException& e)
+    {
+        //log(e.what());
+    }
+
+    return 0;
+}
+
diff --git a/resource/examples/devicediscoveryserver.cpp b/resource/examples/devicediscoveryserver.cpp
new file mode 100644 (file)
index 0000000..4a7494d
--- /dev/null
@@ -0,0 +1,170 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+///This sample demonstrates the device discovery feature
+///The server sets the device related info. which can
+///be later retrieved by a client.
+///
+
+#include <mutex>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+
+//Set of strings for each of deviceInfo fields
+std::string contentType = "myContentType";
+std::string dateOfManufacture = "myDateOfManufacture";
+std::string deviceName = "myDeviceName";
+std::string deviceUUID = "myDeviceUUID";
+std::string firmwareVersion = "myFirmwareVersion";
+std::string hostName = "myHostName";
+std::string manufacturerName = "myManufacturerNa";
+std::string manufacturerUrl = "myManufacturerUrl";
+std::string modelNumber = "myModelNumber";
+std::string platformVersion = "myPlatformVersion";
+std::string supportUrl = "mySupportUrl";
+std::string version = "myVersion";
+
+//OCDeviceInfo Contains all the device info to be stored
+OCDeviceInfo deviceInfo;
+
+void DeleteDeviceInfo()
+{
+    delete deviceInfo.contentType;
+    delete deviceInfo.dateOfManufacture;
+    delete deviceInfo.deviceName;
+    delete deviceInfo.deviceUUID;
+    delete deviceInfo.firmwareVersion;
+    delete deviceInfo.hostName;
+    delete deviceInfo.manufacturerName;
+    delete deviceInfo.manufacturerUrl;
+    delete deviceInfo.modelNumber;
+    delete deviceInfo.platformVersion;
+    delete deviceInfo.supportUrl;
+    delete deviceInfo.version;
+}
+
+void DuplicateString(char ** targetString, std::string sourceString)
+{
+    *targetString = new char[sourceString.length() + 1];
+    strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
+}
+
+OCStackResult SetDeviceInfo(std::string contentType, std::string dateOfManufacture,
+                std::string deviceName, std::string deviceUUID, std::string firmwareVersion,
+                std::string hostName, std::string manufacturerName, std::string manufacturerUrl,
+                std::string modelNumber, std::string platformVersion, std::string supportUrl,
+                std::string version)
+{
+    if(manufacturerName.length() > MAX_MANUFACTURER_NAME_LENGTH)
+    {
+        return OC_STACK_INVALID_PARAM;
+
+    }
+
+    if(manufacturerUrl.length() > MAX_MANUFACTURER_URL_LENGTH)
+    {
+        return OC_STACK_INVALID_PARAM;
+
+    }
+
+    try
+    {
+        DuplicateString(&deviceInfo.contentType, contentType);
+        DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture);
+        DuplicateString(&deviceInfo.deviceName, deviceName);
+        DuplicateString(&deviceInfo.deviceUUID, deviceUUID);
+        DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion);
+        DuplicateString(&deviceInfo.hostName, hostName);
+        DuplicateString(&deviceInfo.manufacturerName, manufacturerName);
+        DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl);
+        DuplicateString(&deviceInfo.modelNumber, modelNumber);
+        DuplicateString(&deviceInfo.platformVersion, platformVersion);
+        DuplicateString(&deviceInfo.supportUrl, supportUrl);
+        DuplicateString(&deviceInfo.version, version);
+    }catch(exception &e)
+    {
+        std::cout<<"String Copy failed!!\n";
+        return OC_STACK_ERROR;
+    }
+
+    return OC_STACK_OK;
+}
+
+
+
+int main()
+{
+
+    // Create PlatformConfig object
+    PlatformConfig cfg {
+        OC::ServiceType::InProc,
+        OC::ModeType::Server,
+        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+        0,         // Uses randomly available port
+        OC::QualityOfService::LowQos
+    };
+
+    OCPlatform::Configure(cfg);
+
+    std::cout<<"Starting server & setting device info\n";
+
+    OCStackResult result = SetDeviceInfo(contentType, dateOfManufacture, deviceName,
+            deviceUUID, firmwareVersion, hostName, manufacturerName, manufacturerUrl,
+            modelNumber, platformVersion, supportUrl, version);
+
+    if(result != OC_STACK_OK)
+    {
+        std::cout << "Device Registration failed\n";
+        return -1;
+    }
+
+    result = OCPlatform::registerDeviceInfo(deviceInfo);
+
+    if(result != OC_STACK_OK)
+    {
+        std::cout << "Device Registration failed\n";
+        return -1;
+    }
+
+    DeleteDeviceInfo();
+
+    // A condition variable will free the mutex it is given, then do a non-
+    // intensive block until 'notify' is called on it.  In this case, since we
+    // don't ever call cv.notify, this should be a non-processor intensive version
+    // of while(true);
+    std::mutex blocker;
+    std::condition_variable cv;
+    std::unique_lock<std::mutex> lock(blocker);
+    cv.wait(lock);
+
+    // No explicit call to stop the platform.
+    // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+    return 0;
+
+}
+
+
+
diff --git a/resource/examples/groupclient.cpp b/resource/examples/groupclient.cpp
new file mode 100755 (executable)
index 0000000..11afb80
--- /dev/null
@@ -0,0 +1,234 @@
+//******************************************************************
+//
+// Copyright 2014 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 "OCPlatform.h"
+#include "OCApi.h"
+
+#include <functional>
+#include <pthread.h>
+#include <iostream>
+
+using namespace std;
+using namespace OC;
+namespace PH = std::placeholders;
+
+OCResourceHandle resourceHandle;
+
+shared_ptr< OCResource > g_resource;
+vector< string > lights;
+
+bool isReady = false;
+
+void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode);
+
+void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
+
+void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
+
+void foundResource(std::shared_ptr< OCResource > resource)
+{
+    std::string resourceURI;
+    std::string hostAddress;
+
+    try
+    {
+        cout << "FOUND Resource" << endl;
+
+        if (resource)
+        {
+            string resourceURI = resource->uri();
+            cout << resourceURI << endl;
+            if (resourceURI == "/core/a/collection")
+            {
+                g_resource = resource;
+            }
+
+            g_resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet);
+            printf("HOST :: %s\n", resource->host().c_str());
+        }
+    }
+    catch (std::exception& e)
+    {
+        std::cout << "" << std::endl;
+    }
+}
+
+void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode)
+{
+    // printf("onGet\n");
+
+    std::vector< OCRepresentation > children = rep.getChildren();
+
+    cout << "\n\n\nCHILD RESOURCE OF GROUP" << endl;
+    for (auto iter = children.begin(); iter != children.end(); ++iter)
+    {
+        lights.push_back((*iter).getUri());
+        cout << "\tURI :: " << (*iter).getUri() << endl;
+    }
+
+    isReady = true;
+}
+
+void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    printf("\nonPut\n");
+}
+
+void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    printf("\nonPost\n");
+
+    std::vector< OCRepresentation > children = rep.getChildren();
+
+    cout << "\n\n\nCHILD RESOURCE OF GROUP" << endl;
+    for (auto iter = children.begin(); iter != children.end(); ++iter)
+    {
+        std::string power;
+        (*iter).getValue("power", power);
+
+        cout << "\tURI :: " << (*iter).getUri() << endl;
+        cout << "\t\tpower :: " << power << endl;
+    }
+
+    if (rep.hasAttribute("ActionSet"))
+    {
+        std::string plainText;
+
+        rep.getValue("ActionSet", plainText);
+
+        printf("\tPlain Text :: %s\n", plainText.c_str());
+    }
+    else
+    {
+        printf("Not found ActionSet\n");
+    }
+}
+
+int main()
+{
+    PlatformConfig config
+    { OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    bool isRun = true;
+
+    try
+    {
+        OCPlatform::Configure(config);
+
+        string resourceTypeName = "a.collection";
+        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=a.collection", &foundResource);
+
+        isReady = false;
+
+        while (isRun)
+        {
+            usleep(100);
+            while (isReady)
+            {
+                int n;
+
+                cout << endl
+                        << "1 :: CREATE ACTIONSET 2 :: EXECUTE ACTION SET 3 :: GET ACTIONSET\n";
+                cout << "4 :: DELETE ACTIONSET 5 :: Quit\n";
+
+                cin >> n;
+                if (n == 1)
+                {
+                    string actionsetDesc;
+                    //"movieTime*uri=coap://10.251.44.228:49858/a/light|power=10*uri=coap://10.251.44.228:49858/a/light|power=10|";
+
+                    actionsetDesc = "allbulboff";
+                    actionsetDesc.append("*");
+                    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+                    {
+                        actionsetDesc.append("uri=").append((*iter));
+                        actionsetDesc.append("|");
+                        actionsetDesc.append("power=");
+                        actionsetDesc.append("off");
+                        if ((iter + 1) != lights.end())
+                        {
+                            actionsetDesc.append("*");
+                        }
+                    }
+
+                    cout << "ActionSet :: " << actionsetDesc << endl;
+
+                    OCRepresentation rep;
+                    rep.setValue("ActionSet", actionsetDesc);
+
+                    if (g_resource)
+                    {
+                        g_resource->put("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
+                                &onPut);
+                    }
+                }
+                else if (n == 2)
+                {
+                    OCRepresentation rep;
+
+                    rep.setValue("DoAction", std::string("allbulboff"));
+
+                    if (g_resource)
+                    {
+                        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
+                                &onPost);
+                    }
+                }
+                else if (n == 3)
+                {
+                    OCRepresentation rep;
+
+                    rep.setValue("GetActionSet", std::string("allbulboff"));
+
+                    if (g_resource)
+                    {
+                        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
+                                &onPost);
+                    }
+                }
+                else if (n == 4)
+                {
+                    OCRepresentation rep;
+
+                    rep.setValue("DelActionSet", std::string("allbulboff"));
+
+                    if (g_resource)
+                    {
+                        g_resource->put("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(),
+                                &onPut);
+                    }
+                }
+                else if (n == 5)
+                {
+                    isRun = false;
+                    break;
+                }
+
+                fflush(stdin);
+            }
+        }
+    }
+    catch (OCException& e)
+    {
+        cout << e.what() << endl;
+    }
+
+    return 0;
+}
diff --git a/resource/examples/groupserver.cpp b/resource/examples/groupserver.cpp
new file mode 100755 (executable)
index 0000000..4cebd44
--- /dev/null
@@ -0,0 +1,129 @@
+//******************************************************************
+//
+// Copyright 2014 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 "OCPlatform.h"
+#include "OCApi.h"
+
+#include <functional>
+#include <pthread.h>
+#include <iostream>
+
+using namespace std;
+using namespace OC;
+
+namespace PH = std::placeholders;
+
+OCResourceHandle resourceHandle;
+std::vector< OCResourceHandle > resourceHandleVector;
+
+void foundResource(std::shared_ptr< OCResource > resource)
+{
+
+    std::string resourceURI;
+    std::string hostAddress;
+
+    try
+    {
+        cout << "FOUND RESOURCE" << endl;
+
+        if (resource)
+        {
+            resourceURI = resource->uri();
+            hostAddress = resource->host();
+
+            cout << "\tResource URI : " << resourceURI << endl;
+            cout << "\tResource Host : " << hostAddress << endl;
+            cout << "\tResource Interfaces : " << resource->getResourceInterfaces().front() << endl;
+            cout << "\tResource Type : " << resource->getResourceTypes().front() << endl;
+            if (resourceURI == "/a/light" || resourceURI == "/a/fan")
+            {
+                OCResourceHandle foundResourceHandle;
+                OCStackResult result = OCPlatform::registerResource(foundResourceHandle, resource);
+                cout << "\tresource registed!" << endl;
+                if (result == OC_STACK_OK)
+                {
+                    OCPlatform::bindResource(resourceHandle, foundResourceHandle);
+                    resourceHandleVector.push_back(foundResourceHandle);
+                }
+                else
+                {
+                    cout << "\tresource Error!" << endl;
+                }
+            }
+
+            // p_platform.bindResource(resourceHandle, foundResourceHandle);
+
+        }
+    }
+    catch (std::exception& e)
+    {
+        std::cout << "" << std::endl;
+    }
+
+}
+
+int main()
+{
+    PlatformConfig config
+    { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    try
+    {
+        string resourceURI = "/core/a/collection";
+        string resourceTypeName = "a.collection";
+        string resourceInterface = BATCH_INTERFACE;
+        OCPlatform::Configure(config);
+
+        // EntityHandler cb = std::bind(, PH::_1, PH::_2);
+
+        OCPlatform::registerResource(resourceHandle, resourceURI, resourceTypeName,
+                resourceInterface,
+                NULL,
+                //&entityHandler, // entityHandler
+                OC_DISCOVERABLE);
+
+        cout << "registerResource is called." << endl;
+
+        OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource);
+        OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
+        OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
+
+        int selectedMenu;
+        while (true)
+        {
+            std::cin >> selectedMenu;
+
+            if (selectedMenu == 1)
+            {
+                for (unsigned int i = 0; i < resourceHandleVector.size(); ++i)
+                {
+                    OCPlatform::unregisterResource(resourceHandleVector.at(i));
+                }
+            }
+
+        }
+    }
+    catch (OCException& e)
+    {
+
+    }
+
+    return 0;
+}
diff --git a/resource/examples/lightserver.cpp b/resource/examples/lightserver.cpp
new file mode 100755 (executable)
index 0000000..f95722d
--- /dev/null
@@ -0,0 +1,334 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample provides steps to define an interface for a resource
+/// (properties and methods) and host this resource on the server.
+///
+
+#include <functional>
+
+#include <pthread.h>
+#include <mutex>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int gObservation = 0;
+void * ChangeLightRepresentation (void *param);
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
+
+// Specifies secure or non-secure
+// false: non-secure resource
+// true: secure resource
+bool isSecure = false;
+
+/// Specifies whether Entity handler is going to do slow response or not
+bool isSlowResponse = false;
+
+// Forward declaring the entityHandler
+
+/// This class represents a single resource named 'lightResource'. This resource has
+/// two simple properties named 'state' and 'power'
+
+class LightResource
+{
+
+public:
+    /// Access this property from a TB client
+    std::string m_power;
+    std::string m_lightUri;
+    OCResourceHandle m_resourceHandle;
+    OCRepresentation m_lightRep;
+
+public:
+    /// Constructor
+    LightResource()
+        :m_power(""), m_lightUri("/a/light") {
+        // Initialize representation
+        m_lightRep.setUri(m_lightUri);
+
+        m_lightRep.setValue("power", m_power);
+    }
+
+    /* Note that this does not need to be a member function: for classes you do not have
+    access to, you can accomplish this with a free function: */
+
+    /// This function internally calls registerResource API.
+    void createResource()
+    {
+        std::string resourceURI = m_lightUri; //URI of the resource
+        std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
+        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+
+        EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1);
+
+        // This will internally create and register the resource.
+        OCStackResult result = OCPlatform::registerResource(
+                                    m_resourceHandle, resourceURI, resourceTypeName,
+                                    resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+        if (OC_STACK_OK != result)
+        {
+            cout << "Resource creation was unsuccessful\n";
+        }
+    }
+
+    OCResourceHandle getHandle()
+    {
+        return m_resourceHandle;
+    }
+
+    // Puts representation.
+    // Gets values from the representation and
+    // updates the internal state
+    void put(OCRepresentation& rep)
+    {
+        try {
+            if (rep.getValue("power", m_power))
+            {
+                cout << "\t\t\t\t" << "power: " << m_power << endl;
+            }
+            else
+            {
+                cout << "\t\t\t\t" << "power not found in the representation" << endl;
+            }
+        }
+        catch (exception& e)
+        {
+            cout << e.what() << endl;
+        }
+
+    }
+
+    // Post representation.
+    // Post can create new resource or simply act like put.
+    // Gets values from the representation and
+    // updates the internal state
+    OCRepresentation post(OCRepresentation& rep)
+    {
+        put(rep);
+        return get();
+    }
+
+
+    // gets the updated representation.
+    // Updates the representation with latest internal state before
+    // sending out.
+    OCRepresentation get()
+    {
+        m_lightRep.setValue("power", m_power);
+
+        return m_lightRep;
+    }
+
+    void addType(const std::string& type) const
+    {
+        OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+    void addInterface(const std::string& interface) const
+    {
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+private:
+// This is just a sample implementation of entity handler.
+// Entity handler can be implemented in several ways by the manufacturer
+OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
+{
+    cout << "\tIn Server CPP entity handler:\n";
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+    if(request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        if(requestFlag & RequestHandlerFlag::InitFlag)
+        {
+            cout << "\t\trequestFlag : Init\n";
+
+            // entity handler to perform resource initialization operations
+        }
+        if(requestFlag & RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\t\trequestFlag : Request\n";
+            auto pResponse = std::make_shared<OC::OCResourceResponse>();
+            pResponse->setRequestHandle(request->getRequestHandle());
+            pResponse->setResourceHandle(request->getResourceHandle());
+
+            // If the request type is GET
+            if(requestType == "GET")
+            {
+                cout << "\t\t\trequestType : GET\n";
+                if(isSlowResponse) // Slow response case
+                {
+                    static int startedThread = 0;
+                    if(!startedThread)
+                    {
+                        std::thread t(handleSlowResponse, (void *)this, request);
+                        startedThread = 1;
+                        t.detach();
+                    }
+                    ehResult = OC_EH_SLOW;
+                }
+                else // normal response case.
+                {
+                    pResponse->setErrorCode(200);
+                    pResponse->setResponseResult(OC_EH_OK);
+                    pResponse->setResourceRepresentation(get());
+                    if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        ehResult = OC_EH_OK;
+                    }
+                }
+            }
+            else if(requestType == "PUT")
+            {
+                cout << "\t\t\trequestType : PUT\n";
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                // Do related operations related to PUT request
+                // Update the lightResource
+                put(rep);
+                pResponse->setErrorCode(200);
+                pResponse->setResponseResult(OC_EH_OK);
+                pResponse->setResourceRepresentation(get());
+                if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
+            }
+            else if(requestType == "POST")
+            {
+                cout << "\t\t\trequestType : POST\n";
+
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                // Do related operations related to POST request
+                OCRepresentation rep_post = post(rep);
+                pResponse->setResourceRepresentation(rep_post);
+                pResponse->setErrorCode(200);
+                if(rep_post.hasAttribute("createduri"))
+                {
+                    pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+                    pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
+                }
+
+                if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
+            }
+            else if(requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+    }
+    else
+    {
+        std::cout << "Request invalid" << std::endl;
+    }
+
+    return ehResult;
+}
+};
+
+void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
+{
+    // This function handles slow response case
+    LightResource* lightPtr = (LightResource*) param;
+    // Induce a case for slow response by using sleep
+    std::cout << "SLOW response" << std::endl;
+    sleep (10);
+
+    auto pResponse = std::make_shared<OC::OCResourceResponse>();
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+    pResponse->setResourceRepresentation(lightPtr->get());
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    // Set the slow response flag back to false
+    isSlowResponse = false;
+    OCPlatform::sendResponse(pResponse);
+    return NULL;
+}
+
+
+int main(int argc, char* argv[])
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg {
+        OC::ServiceType::InProc,
+        OC::ModeType::Server,
+        "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
+        0,         // Uses randomly available port
+        OC::QualityOfService::LowQos
+    };
+
+    OCPlatform::Configure(cfg);
+    try
+    {
+        // Create the instance of the resource class
+        // (in this case instance of class 'LightResource').
+        LightResource myLight;
+
+        // Invoke createResource function of class light.
+        myLight.createResource();
+
+        myLight.addType(std::string("core.brightlight"));
+        myLight.addInterface(std::string("oc.mi.ll"));
+
+        // A condition variable will free the mutex it is given, then do a non-
+        // intensive block until 'notify' is called on it.  In this case, since we
+        // don't ever call cv.notify, this should be a non-processor intensive version
+        // of while(true);
+        std::mutex blocker;
+        std::condition_variable cv;
+        std::unique_lock<std::mutex> lock(blocker);
+        cv.wait(lock);
+    }
+    catch(OCException e)
+    {
+        //log(e.what());
+    }
+
+    // No explicit call to stop the platform.
+    // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+    return 0;
+}
old mode 100644 (file)
new mode 100755 (executable)
index c97f2aa..ec87ec7
@@ -19,7 +19,7 @@
 # //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #
 # override with `make BUILD=release`
-# default to release build
+# default to release build+
 BUILD    := release
 PLATFORM  := linux
 CXX          := g++
@@ -43,11 +43,11 @@ LIB_OC_LOGGER := ../oc_logger/lib/oc_logger.a
 CXX_LIBS  := ../$(BUILD)/obj/liboc.a ../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER)
 
 # Force metatargets to build:
-all.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient ocicuc_target threadingsample
+all.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient ocicuc_target threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver
 
-apps.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample
+apps.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver
 
-buildScript_all.PHONY: prep_dirs simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample
+buildScript_all.PHONY: prep_dirs simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver
 
 all: all.PHONY
 
@@ -103,6 +103,23 @@ garageclient: garageclient.cpp
 threadingsample: threadingsample.cpp
        $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ threadingsample.cpp $(CXX_INC) $(CXX_LIBS)
 
+groupserver: groupserver.cpp
+       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ groupserver.cpp $(CXX_INC) $(CXX_LIBS)
+
+groupclient: groupclient.cpp
+       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ groupclient.cpp $(CXX_INC) $(CXX_LIBS)
+
+lightserver: lightserver.cpp
+       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ lightserver.cpp $(CXX_INC) $(CXX_LIBS)
+
+devicediscoveryserver: devicediscoveryserver.cpp
+       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ devicediscoveryserver.cpp $(CXX_INC) $(CXX_LIBS)
+
+devicediscoveryclient: devicediscoveryclient.cpp
+       $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ devicediscoveryclient.cpp $(CXX_INC) $(CXX_LIBS)
+       
+       
+
 ocicuc_target:
        cd ocicuc && $(MAKE) apps
 
index 6bd79fe..857d0f4 100644 (file)
@@ -41,8 +41,10 @@ static int TEST_CASE = 0;
 typedef enum {
     TEST_UNICAST_PRESENCE_NORMAL = 1,
     TEST_UNICAST_PRESENCE_WITH_FILTER,
+    TEST_UNICAST_PRESENCE_WITH_FILTERS,
     TEST_MULTICAST_PRESENCE_NORMAL,
     TEST_MULTICAST_PRESENCE_WITH_FILTER,
+    TEST_MULTICAST_PRESENCE_WITH_FILTERS,
     MAX_TESTS
 } CLIENT_TEST;
 
@@ -52,9 +54,13 @@ void printUsage()
     std::cout << "-t 1 : Discover Resources and Initiate Unicast Presence" << std::endl;
     std::cout << "-t 2 : Discover Resources and Initiate Unicast Presence with Filter"
               << std::endl;
-    std::cout << "-t 3 : Discover Resources and Initiate Multicast Presence" << std::endl;
-    std::cout << "-t 4 : Discover Resources and Initiate Multicast Presence with Filter"
+    std::cout << "-t 3 : Discover Resources and Initiate Unicast Presence with Two Filters"
+            << std::endl;
+    std::cout << "-t 4 : Discover Resources and Initiate Multicast Presence" << std::endl;
+    std::cout << "-t 5 : Discover Resources and Initiate Multicast Presence with Filter"
               << std::endl;
+    std::cout << "-t 6 : Discover Resources and Initiate Multicast Presence with two Filters"
+                  << std::endl;
 }
 
 // Callback to presence
@@ -123,21 +129,52 @@ void foundResource(std::shared_ptr<OCResource> resource)
 
             if(resourceURI == "/a/light")
             {
+                OCStackResult result = OC_STACK_OK;
                 curResource = resource;
                 OCPlatform::OCPresenceHandle presenceHandle = nullptr;
 
                 if(TEST_CASE == TEST_UNICAST_PRESENCE_NORMAL)
                 {
-                    OCPlatform::subscribePresence(presenceHandle, hostAddress,
+                    result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
                             &presenceHandler);
-                    std::cout<< "Subscribed to unicast address:" << hostAddress <<std::endl;
+                    if(result == OC_STACK_OK)
+                    {
+                        std::cout<< "Subscribed to unicast address: " << hostAddress << std::endl;
+                    }
+                    else
+                    {
+                        std::cout<< "Failed to subscribe to unicast address:" << hostAddress
+                                << std::endl;
+                    }
                 }
-                else if(TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTER)
+                if(TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTER ||
+                        TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTERS)
                 {
-                    OCPlatform::subscribePresence(presenceHandle, hostAddress, "core.light",
+                    result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
+                            "core.light", &presenceHandler);
+                    if(result == OC_STACK_OK)
+                    {
+                        std::cout<< "Subscribed to unicast address: " << hostAddress;
+                    }
+                    else
+                    {
+                        std::cout<< "Failed to subscribe to unicast address: " << hostAddress;
+                    }
+                    std::cout << " with resource type \"core.light\"." << std::endl;
+                }
+                if(TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTERS)
+                {
+                    result = OCPlatform::subscribePresence(presenceHandle, hostAddress, "core.fan",
                             &presenceHandler);
-                    std::cout<< "Subscribed (with resource type) to unicast address:"
-                                << hostAddress << std::endl;
+                    if(result == OC_STACK_OK)
+                    {
+                        std::cout<< "Subscribed to unicast address: " << hostAddress;
+                    }
+                    else
+                    {
+                        std::cout<< "Failed to subscribe to unicast address: " << hostAddress;
+                    }
+                    std::cout << " with resource type \"core.fan\"." << std::endl;
                 }
             }
         }
@@ -191,23 +228,73 @@ int main(int argc, char* argv[]) {
         std::cout << "Created Platform..."<<std::endl;
 
         OCPlatform::OCPresenceHandle presenceHandle = nullptr;
+        OCStackResult result = OC_STACK_OK;
 
         if(TEST_CASE == TEST_MULTICAST_PRESENCE_NORMAL)
         {
-            OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, presenceHandler);
-            std::cout<< "Subscribed to multicast" <<std::endl;
+            result = OCPlatform::subscribePresence(presenceHandle,
+                    OC_MULTICAST_IP, presenceHandler);
+            if(result == OC_STACK_OK)
+            {
+                std::cout << "Subscribed to multicast presence." << std::endl;
+            }
+            else
+            {
+                std::cout << "Failed to subscribe to multicast presence." << std::endl;
+            }
         }
         else if(TEST_CASE == TEST_MULTICAST_PRESENCE_WITH_FILTER)
         {
-            OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.light",
+            result = OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.light",
                     &presenceHandler);
-            std::cout<< "Subscribed to multicast with resource type" <<std::endl;
+            if(result == OC_STACK_OK)
+            {
+                std::cout << "Subscribed to multicast presence with resource type";
+            }
+            else
+            {
+                std::cout << "Failed to subscribe to multicast presence with resource type";
+            }
+            std::cout << "\"core.light\"." << std::endl;
+        }
+        else if(TEST_CASE == TEST_MULTICAST_PRESENCE_WITH_FILTERS)
+        {
+            result = OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.light",
+                    &presenceHandler);
+            if(result == OC_STACK_OK)
+            {
+                std::cout << "Subscribed to multicast presence with resource type";
+            }
+            else
+            {
+                std::cout << "Failed to subscribe to multicast presence with resource type";
+            }
+            std::cout << "\"core.light\"." << std::endl;
+
+            result = OCPlatform::subscribePresence(presenceHandle, OC_MULTICAST_IP, "core.fan",
+                    &presenceHandler);
+            if(result == OC_STACK_OK)
+            {
+                std::cout<< "Subscribed to multicast presence with resource type";
+            }
+            else
+            {
+                std::cout << "Failed to subscribe to multicast presence with resource type.";
+            }
+            std::cout << "\"core.fan\"." << std::endl;
         }
         else
         {
             // Find all resources
-            OCPlatform::findResource("", "coap://224.0.1.187/oc/core", &foundResource);
-            std::cout<< "Finding Resource... " <<std::endl;
+            result = OCPlatform::findResource("", "coap://224.0.1.187/oc/core", &foundResource);
+            if(result == OC_STACK_OK)
+            {
+                std::cout << "Finding Resource... " << std::endl;
+            }
+            else
+            {
+                std::cout << "Failed to request to find resource(s)." << std::endl;
+            }
         }
         //
         // A condition variable will free the mutex it is given, then do a non-
index 63d63da..18e0d7e 100644 (file)
@@ -26,6 +26,7 @@
 #include <functional>
 
 #include <pthread.h>
+#include <array>
 #include <mutex>
 #include <condition_variable>
 
@@ -35,6 +36,8 @@
 using namespace OC;
 using namespace std;
 
+#define numPresenceResources (2)
+
 // Forward declaring the entityHandler
 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
 
@@ -149,6 +152,35 @@ public:
 
 };
 
+void createPresenceResources()
+{
+    std::array<std::string, numPresenceResources> resourceURI { {
+        "/a/fan",
+        "/a/led" } };
+    std::array<std::string, numPresenceResources> resourceTypeName { {
+        "core.fan",
+        "core.led" } };
+
+    std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+    OCResourceHandle handle;
+    // OCResourceProperty is defined ocstack.h
+    uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+
+    // This will internally create and register the resource.
+    OCStackResult result = OC_STACK_OK;
+    for(int i=0; i<numPresenceResources; i++)
+    {
+        result = OCPlatform::registerResource(handle,
+                resourceURI.at(i), resourceTypeName.at(i), resourceInterface,
+                &entityHandler, resourceProperty);
+        if (result != OC_STACK_OK)
+        {
+            cout << "Resource creation was unsuccessful with resource URI "
+                    << resourceURI.at(i);
+        }
+    }
+}
+
 // Create the instance of the resource class (in this case instance of class 'LightResource').
 LightResource myLightResource;
 
@@ -178,8 +210,9 @@ int main()
 
         // Invoke createResource function of class light.
         myLightResource.createResource();
+        printf("Created first resource of type \"core.light\"");
 
-        printf("\nEnter a key to create the second resource\n");
+        printf("\nEnter a key to create the second resource of type \"core.light\"\n");
         getchar();
 
         myLightResource.createResource2();
@@ -193,11 +226,16 @@ int main()
 
         startPresence(30);
 
-        printf("\nEnter a key to create the third resource\n");
+        printf("\nEnter a key to create the third resource of type \"core.light\"\n");
         getchar();
 
         myLightResource.createResource3();
 
+        printf("\nEnter a key to create two non-operational resources.\"\n");
+        getchar();
+
+        createPresenceResources();
+
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
         // don't ever call cv.notify, this should be a non-processor intensive version
index 8ec23a5..1e40e23 100644 (file)
@@ -44,6 +44,10 @@ namespace OC
                         const std::string& resourceType, FindCallback& callback,
                         QualityOfService QoS) = 0;
 
+        virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
+                        const std::string& deviceURI, FindDeviceCallback& callback,
+                        QualityOfService QoS) = 0;
+
         virtual OCStackResult GetResourceRepresentation(const std::string& host,
                         const std::string& uri, const QueryParamsMap& queryParams,
                         const HeaderOptions& headerOptions,
index 10e0515..c6c0b2d 100644 (file)
@@ -51,6 +51,9 @@ namespace OC
                     EntityHandler& entityHandler,
                     uint8_t resourceProperty) = 0;
 
+        virtual OCStackResult registerDeviceInfo(
+                    const OCDeviceInfo deviceInfo) = 0;
+
         virtual OCStackResult registerResourceWithHost(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceHOST,
index 9ca0779..ced111d 100644 (file)
@@ -52,6 +52,12 @@ namespace OC
             std::weak_ptr<IClientWrapper> clientWrapper;
         };
 
+        struct DeviceListenContext
+        {
+            FindDeviceCallback callback;
+            IClientWrapper::Ptr clientWrapper;
+        };
+
         struct SubscribePresenceContext
         {
             SubscribeCallback callback;
@@ -81,6 +87,10 @@ namespace OC
             const std::string& resourceType, FindCallback& callback,
             QualityOfService QoS);
 
+        virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
+            const std::string& deviceURI, FindDeviceCallback& callback,
+            QualityOfService QoS);
+
         virtual OCStackResult GetResourceRepresentation(const std::string& host,
             const std::string& uri, const QueryParamsMap& queryParams,
             const HeaderOptions& headerOptions,
index aab856b..b68f599 100644 (file)
@@ -45,6 +45,9 @@ namespace OC
                     EntityHandler& entityHandler,
                     uint8_t resourceProperty);
 
+        virtual OCStackResult registerDeviceInfo(
+                    const OCDeviceInfo deviceInfo);
+
         virtual OCStackResult registerResourceWithHost(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceHOST,
index 97076c5..b523da5 100644 (file)
@@ -194,8 +194,14 @@ namespace OC
     // Used in GET, PUT, POST, DELETE methods on links to other resources of a collection.
     const std::string BATCH_INTERFACE = "oc.mi.b";
 
+    // Used in GET, PUT, POST methods on links to other remote resources of a group.
+    const std::string GROUP_INTERFACE = "oc.mi.c";
+
+
     typedef std::function<void(std::shared_ptr<OCResource>)> FindCallback;
 
+    typedef std::function<void(const OCRepresentation&)> FindDeviceCallback;
+
     typedef std::function<OCEntityHandlerResult(
                             const std::shared_ptr<OCResourceRequest>)> EntityHandler;
 
index 61a0f48..1cad339 100644 (file)
@@ -120,6 +120,21 @@ namespace OC
                     FindCallback resourceHandler, QualityOfService QoS);
 
         /**
+         * API for Device Discovery
+         *
+         *
+         * @param host - Host IP Address. If null or empty, Multicast is performed.
+         * @param resourceURI - Uri containing address to the virtual device in C Stack
+                                ("/oc/core/d")
+         * @param QualityOfService the quality of communication
+         *
+         */
+        OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
+                    FindDeviceCallback deviceInfoHandler);
+        OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
+                    FindDeviceCallback deviceInfoHandler, QualityOfService QoS);
+
+        /**
         * This API registers a resource with the server
         * NOTE: This API applies to server side only.
         *
@@ -167,6 +182,18 @@ namespace OC
                         const std::shared_ptr< OCResource > resource);
 
         /**
+         * Register Device Info
+         *
+         * @param deviceInfo - structure containing all the device specific information
+         *
+         * @return
+         *      OC_STACK_OK   - no errors
+         *      OC_STACK_ERROR - stack process error
+         */
+
+        OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo);
+
+        /**
         * Set default device entity handler
         *
         * @param entityHandler - entity handler to handle requests for
index 896ce3a..f25ce2e 100644 (file)
@@ -146,6 +146,21 @@ namespace OC
                     FindCallback resourceHandler, QualityOfService QoS);
 
         /**
+         * API for Device Discovery
+         *
+         * @param host - Host IP Address. If null or empty, Multicast is performed.
+         * @param resourceURI - Uri containing address to the virtual device in C Stack
+         *                       ("/oc/core/d")
+         *
+         * @param QualityOfService the quality of communication
+         *
+         */
+        OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
+                    FindDeviceCallback deviceInfoHandler);
+        OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
+                    FindDeviceCallback deviceInfoHandler, QualityOfService QoS);
+
+        /**
         * This API registers a resource with the server
         * NOTE: This API applies to server side only.
         *
@@ -193,6 +208,17 @@ namespace OC
                         const std::shared_ptr<OCResource> resource);
 
         /**
+         * This API registers all the device specific information
+         *
+         * @param OCDeviceInfo - Structure containing all the device related information
+         *
+         * @return OCStackResult return value of the API. Returns OC_STACK_OK if success
+         *
+         * Note: OCDeviceInfo is defined in OCStack.h
+         */
+        OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo);
+
+        /**
         * Set default device entity handler
         *
         * @param entityHandler - entity handler to handle requests for
index dfae653..049c445 100644 (file)
@@ -36,6 +36,11 @@ namespace OC
             const std::string& resourceType, FindCallback& callback, QualityOfService QoS)
             {return OC_STACK_NOTIMPL;}
 
+        virtual OCStackResult ListenForDevice(const std::string& serviceUrl,
+            const std::string& deviceURI, FindDeviceCallback& callback,
+            QualityOfService QoS)
+            {return OC_STACK_NOTIMPL;}
+
         virtual OCStackResult GetResourceRepresentation(const std::string& host,
             const std::string& uri, const QueryParamsMap& queryParams,
             const HeaderOptions& headerOptions, GetCallback& callback,
index be51f3d..91c6f15 100644 (file)
@@ -43,6 +43,14 @@ namespace OC
             // Not implemented
             return OC_STACK_NOTIMPL;
         }
+
+        virtual OCStackResult registerDeviceInfo(
+                    const OCDeviceInfo deviceInfo)
+        {
+            // Not implemented
+            return OC_STACK_NOTIMPL;
+        }
+
         virtual OCStackResult registerResourceWithHost(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceHOST,
index b29fb0c..048a476 100644 (file)
@@ -87,6 +87,7 @@ namespace OC
         static const std::string OBSV_NOT_REMOVED           = "Stack observer not removed";
         static const std::string STACK_RESOURCE_DELETED     = "The specified resource has been deleted";
         static const std::string PRESENCE_STOPPED           = "Stack presence stopped";
+        static const std::string PRESENCE_TIMEOUT           = "Stack presence timed out";
         static const std::string PRESENCE_NOT_HANDLED       = "Stack presence should not be handled";
         static const std::string INVALID_OPTION             = "Invalid option";
         static const std::string GENERAL_FAULT              = "General Fault";
index e9580b2..83e4ef8 100644 (file)
@@ -92,6 +92,33 @@ namespace OC
         }
     }
 
+    OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
+    {
+        if(clientResponse->resJSONPayload == nullptr || clientResponse->resJSONPayload[0] == '\0')
+        {
+            throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_ERROR);
+        }
+
+        MessageContainer oc;
+        oc.setJSONRepresentation(clientResponse->resJSONPayload);
+
+        std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
+        if(it == oc.representations().end())
+        {
+            throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_ERROR);
+        }
+
+        // first one is considered the root, everything else is considered a child of this one.
+        OCRepresentation root = *it;
+        ++it;
+
+        std::for_each(it, oc.representations().end(),
+                [&root](const OCRepresentation& repItr)
+                {root.addChild(repItr);});
+        return root;
+
+    }
+
     OCStackApplicationResult listenCallback(void* ctx, OCDoHandle handle,
         OCClientResponse* clientResponse)
     {
@@ -143,7 +170,6 @@ namespace OC
         }
 
         return OC_STACK_KEEP_TRANSACTION;
-
     }
 
     OCStackResult InProcClientWrapper::ListenForResource(const std::string& serviceUrl,
@@ -181,31 +207,52 @@ namespace OC
         return result;
     }
 
-    OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse)
+    OCStackApplicationResult listenDeviceCallback(void* ctx, OCDoHandle handle,
+            OCClientResponse* clientResponse)
     {
-        if(clientResponse->resJSONPayload == nullptr || clientResponse->resJSONPayload[0] == '\0')
-        {
-            return OCRepresentation();
-        }
+        ClientCallbackContext::DeviceListenContext* context =
+            static_cast<ClientCallbackContext::DeviceListenContext*>(ctx);
 
-        MessageContainer oc;
-        oc.setJSONRepresentation(clientResponse->resJSONPayload);
+        OCRepresentation rep = parseGetSetCallback(clientResponse);
+        std::thread exec(context->callback, rep);
+        exec.detach();
 
-        std::vector<OCRepresentation>::const_iterator it = oc.representations().begin();
-        if(it == oc.representations().end())
-        {
-            return OCRepresentation();
-        }
+        return OC_STACK_KEEP_TRANSACTION;
+    }
 
-        // first one is considered the root, everything else is considered a child of this one.
-        OCRepresentation root = *it;
-        ++it;
+    OCStackResult InProcClientWrapper::ListenForDevice(const std::string& serviceUrl,
+        const std::string& deviceURI, FindDeviceCallback& callback, QualityOfService QoS)
+    {
+        OCStackResult result;
 
-        std::for_each(it, oc.representations().end(),
-                [&root](const OCRepresentation& repItr)
-                {root.addChild(repItr);});
-        return root;
+        OCCallbackData cbdata = {0};
 
+        ClientCallbackContext::DeviceListenContext* context =
+            new ClientCallbackContext::DeviceListenContext();
+        context->callback = callback;
+        context->clientWrapper = shared_from_this();
+
+        cbdata.context =  static_cast<void*>(context);
+        cbdata.cb = listenDeviceCallback;
+        cbdata.cd = [](void* c){delete static_cast<ClientCallbackContext::DeviceListenContext*>(c);};
+
+        auto cLock = m_csdkLock.lock();
+        if(cLock)
+        {
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+            OCDoHandle handle;
+            result = OCDoResource(&handle, OC_REST_GET,
+                                  deviceURI.c_str(),
+                                  nullptr, nullptr,
+                                  static_cast<OCQualityOfService>(QoS),
+                                  &cbdata,
+                                  NULL, 0);
+        }
+        else
+        {
+            result = OC_STACK_ERROR;
+        }
+        return result;
     }
 
     void parseServerHeaderOptions(OCClientResponse* clientResponse,
index c92a036..0159bb8 100644 (file)
@@ -271,6 +271,18 @@ namespace OC
         }
     }
 
+    OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo)
+    {
+        auto cLock = m_csdkLock.lock();
+        OCStackResult result = OC_STACK_ERROR;
+        if(cLock)
+        {
+            std::lock_guard<std::recursive_mutex> lock(*cLock);
+            result = OCSetDeviceInfo(deviceInfo);
+        }
+        return result;
+    }
+
     OCStackResult InProcServerWrapper::registerResource(
                     OCResourceHandle& resourceHandle,
                     std::string& resourceURI,
@@ -351,7 +363,7 @@ namespace OC
                         resourceTypeName.c_str(), // const char * resourceTypeName
                         resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix
                         resourceHOST.c_str(), // const char * host
-                        resourceURI.c_str(), // const char * uri
+                        (resourceHOST + resourceURI).c_str(), // const char * uri
                         EntityHandlerWrapper, // OCEntityHandler entityHandler
                         resourceProperties // uint8_t resourceProperties
                         );
@@ -362,7 +374,7 @@ namespace OC
                         resourceTypeName.c_str(), // const char * resourceTypeName
                         resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix
                         resourceHOST.c_str(), // const char * host
-                        resourceURI.c_str(), // const char * uri
+                        (resourceHOST + resourceURI).c_str(), // const char * uri
                         nullptr, // OCEntityHandler entityHandler
                         resourceProperties // uint8_t resourceProperties
                         );
index 97381e5..9bea2e2 100644 (file)
@@ -66,6 +66,10 @@ std::string OC::OCException::reason(const OCStackResult sr)
 #ifdef WITH_PRESENCE
         case OC_STACK_PRESENCE_STOPPED:
             return OC::Exception::PRESENCE_STOPPED;
+        case OC_STACK_PRESENCE_TIMEOUT:
+            return OC::Exception::PRESENCE_TIMEOUT;
+        case OC_STACK_PRESENCE_DO_NOT_HANDLE:
+            return OC::Exception::PRESENCE_NOT_HANDLED;
 #endif
         case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
             return OC::Exception::VIRTUAL_DO_NOT_HANDLE;
index f26ffc7..9a17833 100644 (file)
@@ -95,6 +95,22 @@ namespace OC
                                                 resourceHandler, QoS);
         }
 
+        OCStackResult getDeviceInfo(const std::string& host,
+                                                const std::string& deviceURI,
+                                                FindDeviceCallback deviceInfoHandler)
+        {
+            return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, deviceInfoHandler);
+        }
+
+        OCStackResult getDeviceInfo(const std::string& host,
+                                                const std::string& deviceURI,
+                                                FindDeviceCallback deviceInfoHandler,
+                                                QualityOfService QoS)
+        {
+            return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI,
+                    deviceInfoHandler, QoS);
+        }
+
 
         OCStackResult registerResource(OCResourceHandle& resourceHandle,
                                                 std::string& resourceURI,
@@ -114,6 +130,11 @@ namespace OC
             return OCPlatform_impl::Instance().registerResource(resourceHandle, resource);
         }
 
+        OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo)
+        {
+            return OCPlatform_impl::Instance().registerDeviceInfo(deviceInfo);
+        }
+
         OCStackResult unregisterResource(const OCResourceHandle& resourceHandle)
         {
             return OCPlatform_impl::Instance().unregisterResource(resourceHandle);
index e99cea7..9d9ae52 100644 (file)
@@ -172,6 +172,21 @@ namespace OC
                              host, resourceName, resourceHandler, QoS);
     }
 
+    OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
+                                            const std::string& deviceURI,
+                                            FindDeviceCallback deviceInfoHandler)
+    {
+        return result_guard(getDeviceInfo(host, deviceURI, deviceInfoHandler, m_cfg.QoS));
+    }
+
+    OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host,
+                                            const std::string& deviceURI,
+                                            FindDeviceCallback deviceInfoHandler,
+                                            QualityOfService QoS)
+    {
+        return checked_guard(m_client, &IClientWrapper::ListenForDevice,
+                             host, deviceURI, deviceInfoHandler, QoS);
+    }
 
     OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                             std::string& resourceURI,
@@ -185,17 +200,22 @@ namespace OC
                              resourceInterface, entityHandler, resourceProperty);
     }
 
+    OCStackResult OCPlatform_impl::registerDeviceInfo(const OCDeviceInfo deviceInfo)
+    {
+        return checked_guard(m_server, &IServerWrapper::registerDeviceInfo, deviceInfo);
+    }
 
-       OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
+    OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle,
                                             const std::shared_ptr< OCResource > resource)
     {
         uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+        std::vector<std::string> resourceTypes = resource->getResourceTypes();
 
         return checked_guard(m_server, &IServerWrapper::registerResourceWithHost,
-                ref(resourceHandle), resource->host(), resource->uri(), "core.remote", "oc.mi.def",
+                ref(resourceHandle), resource->host(), resource->uri(), resourceTypes[0]/*"core.remote"*/, "oc.mi.def",
                 (EntityHandler) nullptr, resourceProperty);
-
     }
+
     OCStackResult OCPlatform_impl::unregisterResource(const OCResourceHandle& resourceHandle) const
     {
         return checked_guard(m_server, &IServerWrapper::unregisterResource,
index c55d8f9..530f673 100644 (file)
@@ -203,6 +203,8 @@ OCStackResult result_guard(const OCStackResult r)
     case OC_STACK_OBSERVER_NOT_FOUND:
 #ifdef WITH_PRESENCE
     case OC_STACK_PRESENCE_STOPPED:
+    case OC_STACK_PRESENCE_TIMEOUT:
+    case OC_STACK_PRESENCE_DO_NOT_HANDLE:
 #endif
 
     break;
diff --git a/service/docs/Control Manager-Programmer's guide.pdf b/service/docs/Control Manager-Programmer's guide.pdf
new file mode 100644 (file)
index 0000000..f5fe8a5
Binary files /dev/null and b/service/docs/Control Manager-Programmer's guide.pdf differ
diff --git a/service/docs/Getting Started_IoTivity Services_20141218.pdf b/service/docs/Getting Started_IoTivity Services_20141218.pdf
new file mode 100755 (executable)
index 0000000..360143d
Binary files /dev/null and b/service/docs/Getting Started_IoTivity Services_20141218.pdf differ
diff --git a/service/docs/Getting Started_SSM_PPM_Things Manager_NM_20141218.pdf b/service/docs/Getting Started_SSM_PPM_Things Manager_NM_20141218.pdf
new file mode 100755 (executable)
index 0000000..3172d78
Binary files /dev/null and b/service/docs/Getting Started_SSM_PPM_Things Manager_NM_20141218.pdf differ
diff --git a/service/docs/IoTivity Services_20141216.pdf b/service/docs/IoTivity Services_20141216.pdf
new file mode 100644 (file)
index 0000000..ff8f4ba
Binary files /dev/null and b/service/docs/IoTivity Services_20141216.pdf differ
diff --git a/service/docs/Notification Manager - Programmer's guide.pdf b/service/docs/Notification Manager - Programmer's guide.pdf
new file mode 100644 (file)
index 0000000..2d91b78
Binary files /dev/null and b/service/docs/Notification Manager - Programmer's guide.pdf differ
diff --git a/service/docs/PPM - Programmer's Guide_20141218.pdf b/service/docs/PPM - Programmer's Guide_20141218.pdf
new file mode 100755 (executable)
index 0000000..bfc3915
Binary files /dev/null and b/service/docs/PPM - Programmer's Guide_20141218.pdf differ
diff --git a/service/docs/SSM - Programmer's guide_20141216.pdf b/service/docs/SSM - Programmer's guide_20141216.pdf
new file mode 100755 (executable)
index 0000000..5ecc3a4
Binary files /dev/null and b/service/docs/SSM - Programmer's guide_20141216.pdf differ
diff --git a/service/docs/Things Manager - Programmer's guide_M2_SDK_APIs.pdf b/service/docs/Things Manager - Programmer's guide_M2_SDK_APIs.pdf
new file mode 100644 (file)
index 0000000..ab356e1
Binary files /dev/null and b/service/docs/Things Manager - Programmer's guide_M2_SDK_APIs.pdf differ
index dafa22e..a3f6aa1 100644 (file)
@@ -23,7 +23,7 @@ sample-app:
        cd $(PROTOCOL_ROOT)sample-app/linux/mqtt && $(MAKE)
        cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libpmimpl.so $(PROTOCOL_ROOT)sample-app/linux/mqtt/
        cp -Rdp $(PROTOCOL_ROOT)sample-app/linux/mqtt/mqttclient release/
-       
+       cp -Rdp $(PROTOCOL_ROOT)sample-app/linux/mqtt/pluginmanager.xml release/
 
 clean:
        cd $(PROTOCOL_ROOT)plugin-manager/build/linux && $(MAKE) clean
index 528c7dd..d473421 100644 (file)
@@ -51,6 +51,10 @@ PMRESULT Config::loadConfigFile(const std::string configfilepath)
 {
     // Read the xml file
     std::ifstream xmlFile(configfilepath.c_str());
+    if(!xmlFile.good())
+    {
+        return PM_S_FALSE;
+    }
     xml_document<> doc;
     //into a vector
     std::vector<char> buffer((istreambuf_iterator<char>(xmlFile)), istreambuf_iterator<char>());
index c3abdb8..7e0f0ed 100644 (file)
@@ -29,7 +29,7 @@ using namespace OIC;
 
 PluginManager::PluginManager()
 {
-    void *handle = dlopen("./libpmimpl.so", RTLD_LAZY);
+    handle = dlopen("./libpmimpl.so", RTLD_LAZY);
     if (!handle)
     {
         fprintf(stderr, "%s\n", dlerror());
@@ -44,6 +44,7 @@ PluginManager::PluginManager()
 PluginManager::~PluginManager(void)
 {
     destroy(pluginManagerImpl);
+    free(handle);
 }
 
 int PluginManager::startPlugins(const std::string key, const std::string value)
index 2ae8b73..12c11ab 100644 (file)
@@ -96,6 +96,7 @@ namespace OIC
         private:
             PluginManagerImpl *pluginManagerImpl;
             void (*destroy)(PluginManagerImpl *);
+            void *handle;
     };
 }
 #endif //__PLUGINMANAGER_H
index 351756b..c9f3ad2 100644 (file)
@@ -41,12 +41,12 @@ The Protocol Plug-in directory includes following sub directories;
 2. Compiling C-Pluff library 
 Before building Protocol-Plugin Manager, C-Pluff library should be compiled as follows.
 
-~/oic/oic-service/protocol-plugin/lib/cpluff$ aclocal
-~/oic/oic-service/protocol-plugin/lib/cpluff$ autoconf
-~/oic/oic-service/protocol-plugin/lib/cpluff$ autoheader
-~/oic/oic-service/protocol-plugin/lib/cpluff$ automake
-~/oic/oic-service/protocol-plugin/lib/cpluff$ ./configure
-~/oic/oic-service/protocol-plugin/lib/cpluff$ make
+~/service/protocol-plugin/lib/cpluff$ aclocal
+~/service/protocol-plugin/lib/cpluff$ autoconf
+~/service/protocol-plugin/lib/cpluff$ autoheader
+~/service/protocol-plugin/lib/cpluff$ automake
+~/service/protocol-plugin/lib/cpluff$ ./configure
+~/service/protocol-plugin/lib/cpluff$ make
 
  
 3. Run make
@@ -54,7 +54,7 @@ By running make in the protocol-plugin path, protocol-plugin manager, all plugin
  
 NOTE: To build plugins in 64-bit Ubuntu Linux, OCLib.a and libcoap.a library should be re-compiled with ?fPIC option.
  
-~/oic/oic-service/protocol-plugin/build/linux$make
+~/service/protocol-plugin/build/linux$make
 
 
 4. Using Plugins 
@@ -63,6 +63,8 @@ This version of protocol plug-in source code has following functionality.
 1) provides plug-in manager which can start and stop plug-in library.
 2) provides plug-in library which can communicate with MQTT protocol Fan and Light.
 3) provides OIC Sample Client which can get info about Fan and Light with configuration file(pluginmanager.xml).
+   before starting sample app need as below command. 
+   $export LD_LIBRARY_PATH={Top_Dir}/out/linux/x86/release/:$LD_LIBRARY_PATH
 
 So, to test a plug-in, follow below steps.
 
@@ -70,6 +72,6 @@ So, to test a plug-in, follow below steps.
 2) Register the plug-in with directory path input from plug-in manager sample.
 3) Start the plug-in from plug-in manager sample.
 4) Run OIC sample client.
-   ex)service/protocol-plugin/sample-app/linux/mqtt$./mqttclient
+   ex)~service/protocol-plugin/sample-app/linux/mqtt$./mqttclient
   (mqtt broker is already installed in the local system.)
 
index eda93d4..59ec85d 100644 (file)
@@ -54,6 +54,21 @@ class Fan
 
 Fan myfan;
 
+class Light
+{
+    public:
+
+        bool m_state;
+        int m_power;
+        std::string m_name;
+
+        Light() : m_state(false), m_power(0), m_name("")
+        {
+        }
+};
+
+Light mylight;
+
 int observe_count()
 {
     static int oc = 0;
@@ -237,11 +252,11 @@ void putFanRepresentation(std::shared_ptr<OCResource> resource)
 }
 
 // Callback handler on GET request
-void onGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+void onFanGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
 {
     if (eCode == OC_STACK_OK)
     {
-        std::cout << "GET request was successful" << std::endl;
+        std::cout << "GET Fan request was successful" << std::endl;
         std::cout << "Resource URI: " << rep.getUri() << std::endl;
 
         rep.getValue("state", myfan.m_state);
@@ -261,6 +276,29 @@ void onGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, cons
     }
 }
 
+void onLightGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        std::cout << "GET Light request was successful" << std::endl;
+        std::cout << "Resource URI: " << rep.getUri() << std::endl;
+
+        rep.getValue("state", mylight.m_state);
+        rep.getValue("power", mylight.m_power);
+        rep.getValue("name", mylight.m_name);
+
+        std::cout << "\tstate: " << mylight.m_state << std::endl;
+        std::cout << "\tpower: " << mylight.m_power << std::endl;
+        std::cout << "\tname: " << mylight.m_name << std::endl; 
+    }
+    else
+    {
+        std::cout << "onGET Response error: " << eCode << std::endl;
+        std::exit(-1);
+    }
+}
+
+
 // Local function to get representation of fan resource
 void getFanRepresentation(std::shared_ptr<OCResource> resource)
 {
@@ -270,7 +308,7 @@ void getFanRepresentation(std::shared_ptr<OCResource> resource)
         // Invoke resource's get API with the callback parameter
 
         QueryParamsMap test;
-        resource->get(test, &onGet);
+        resource->get(test, &onFanGet);
     }
 }
 
@@ -282,7 +320,7 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
         // Invoke resource's get API with the callback parameter
 
         QueryParamsMap test;
-        resource->get(test, &onGet);
+        resource->get(test, &onLightGet);
     }
 }
 
@@ -531,7 +569,7 @@ int main(int argc, char *argv[])
         std::cout << "======================" << std::endl;
         std::cout << "Start Fan Plugin by Name\n" << std::endl;
 
-        name = user_plugin[0].getName().c_str();
+        name = user_plugin[0].getName();
         m_pm->startPlugins(key, name);
 
         sleep(5);
index fb078ff..1e295bf 100644 (file)
-Before run make,                                                                   
-                                                                                   
-you have to modify Soft Sensor repository path                                     
-                                                                                   
-that Soft Sensor Manager can find assets while it starts.                          
-                                                                                   
-                                                                                   
-If you want to build THSensorApp for Arduino, let's install follow.
-$ sudo apt-get install arduino
+/******************************************************************
+*
+* Copyright 2014 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.
+*
+******************************************************************/
 
-Download Time library(Time.zip) from http://playground.arduino.cc/Code/Time 
-Unzip Time.zip to /usr/share/arduino/libraries/Time.
 
-$ sudo cp -Rdp THSensorApp/Time /usr/share/arduino/libraries/
+===============================================================================
+==                How to       Build SoftSensorManager                          ==
+===============================================================================
 
-Open the file located at "THSensorApp/build/Makefile"
+Once the source code is downloaded in your local specific folder, you may follow 
+the steps to build and execute Soft Sensor Manager and its applications. 
+In this context, we assume that the code was downloaded into 'oic' folder.
 
-Line 9, ARDUINO_PORT is the serial port path,
 
-which has to be aligned on your system.
+=======================================
+1. Download source code
+=======================================
 
+Once you download the codes, please make sure that the downloaded code structure is as follows; 
 
-If you type "make" at SoftSensorManager folder.
+oic/resource 
+oic/service
+oic/utilities
+The path for Soft Sensor Manager is as following;
 
-All packages will be pushed to "Outputs" folder.
+oic/service/soft-sensor-manager
+The SoftSensorManager directory includes following sub directories;
 
-You can also found other packages from their.
+Directories    Description
+oic/service/soft-sensor-manager/build            : There are makefiles for different platform; Linux, Tizen, and Arduino.  
+oic/service/soft-sensor-manager/doc              : SSM developer's guide and Getting started documents
+oic/service/soft-sensor-manager/SampleApp        : There are two types of sample applications; application for UI, and application for physical sensors.
+                                                   For UI application, there are SSMTesterApp in /linux, and /Tizen.
+                                                   For physical sensors, 
+                                                        1) Temperature and Humidity sensors, THSensorApp, in \linux and \arduino.
+                                                           In the two directories, in \linux and \arduino , there are two TemperaterHumiditySensor applications, 
+                                                           THSensorApp and THSensorApp1, and they are for DiscomfortSoftSensor which aggregates 
+                                                           two TemperaterHumiditySensors to calculate current discomfort index in the given room.
+                                                        2) Trackee_Thing for IndoorTrajectorySensor in \linux and \arduino
+oic/service/soft-sensor-manager/SDK              : The SDK APIs for applications is located.
+oic/service/soft-sensor-manager/SSMCore          : The SSM service codes 
+oic/service/soft-sensor-manager/SoftSensorPlugin : The source codes for soft sensors can be located in this folder. 
+                                                       Examples of soft sensors are DiscomfortIndexSensor and IndoorTrajectorySensor.
+
+
+=======================================
+2. Refer readme files in each build 
+   directory for each module.
+=======================================
+There are readme files in the build directories for each module (e.g. \SDK, \ SSMCore,  \SampleApp). 
+Please refer the files for specific setup.
+
+
+=======================================
+3. Run make
+=======================================
+
+3.1 Run make for SoftSensorManager & App in Ubuntu. 
+
+3.1.1 Before running make for SoftSensorManager & App in Ubuntu, resource should be built in advance. 
+   Please refer to ¡®Build the IoTivity project for Linux¡¯ in previous section
+
+3.1.2 If you type "make" at ¡°soft-sensor-manager/build/linux¡±, all packages will be pushed to "/soft-sensor-manager/build/linux/release".  
+   You can also found other packages in the folder
+
++--------------------------------------------------------------+
+| ~/oic/service/soft-sensor-manager/build/linux$ make          |
++--------------------------------------------------------------+
+
+3.2 Run make for App in Arduino
+
+3.2.1 If you want to build for Arduino, download Arduino IDE (Arduino 1.0.6) from following url. 
+   Extract ¡®arduino-1.0.6-linux32.tgz¡¯ and change folder name from ¡®arduino-1.0.6¡¯ to ¡®arduino¡¯ and then move to "/usr/share/".
+   url: http://arduino.cc/en/Main/Software
+
++--------------------------------------------------------------------+
+| $ mv arduino-1.0.6 arduino                                         |
+| $ sudo cp -Rdp ./arduino /usr/share/                               |
++--------------------------------------------------------------------+
+  
+3.2.2 Download Time library (Time.zip, Click ¡°The download¡±) from following url. 
+   Unzip Time.zip and move them to /usr/share/arduino/libraries.  
+   url: http://playground.arduino.cc/Code/Time
+
++--------------------------------------------------------------------+
+| $ sudo cp -Rdp ./Time /usr/share/arduino/libraries/                |
++--------------------------------------------------------------------+
+
+3.2.3 Create file named ¡®local.properties¡¯ in  ¡°/oic/resource/csdk/¡± with the following definitions.
+
++------------------------------------------------------------------------------------+
+| < local.properties >                                                               |
+| ARDUINO_DIR = /usr/share/arduino                                                   |
+| ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin                          |
++------------------------------------------------------------------------------------+
+   If you have a problem with compiling ¡®resource¡¯ when you compile arduino application, 
+   you may need to check 'local.properties' which is written in the readme file, '/oic/resource/csdk/README'.
+
+3.2.4 Before running make for application, you need to build resource with arduino platform first. 
+   Please refer to below example.
+
++------------------------------------------------------------------------------------------+
+| ~/oic/resource/csdk$ make PLATFORM=arduinomega ARDUINOWIFI=1                             |
++------------------------------------------------------------------------------------------+
+   PLATFORM :  arduinomega or arduinodue.
+   ARDUINOWIFI : 0 (Ethernet), 1(Wifi)
+
+3.2.5 Now, you are ready to build sample arduino application. 
+   To build all sample  applications for arduino, just do as below.
+
++------------------------------------------------------------------------------------------------+
+|~/oic/service/soft-sensor-manager/ build/Arduino$ make PLATFORM=arduinomega ARDUINOWIFI=1       |                           
++------------------------------------------------------------------------------------------------+ 
+
+   If you want to build each sample application separately, go to build directory for sample application. 
+   Belowing is example for THSensor App. 
+   
++-------------------------------------------------------------------------------------------------------------------+
+|~/oic/service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build$ make PLATFORM=arduinomega ARDUINOWIFI=1     |                           
++-------------------------------------------------------------------------------------------------------------------+ 
+
+3.2.6. To build and deploy the binary into the target hardware board, Aruino in this case, you need 'install' option. 
+   Please refer to below example for THSensorApp;
+
++--------------------------------------------------------------------------------------------------------------------------+
+|~/oic/service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build$ make install PLATFORM=arduinomega ARDUINOWIFI=1    |                           
++--------------------------------------------------------------------------------------------------------------------------+ 
+   Before ¡®make install¡¯, you need to check the file located at "/oic/service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/Makefile". 
+   Line 26, ARDUINO_PORT is the serial port path, which has to be aligned on your system.  
+
+
+=======================================
+4. Execute THSensorApp and SSMTesterApp
+=======================================
+
+If you want to check how soft-sensor-manager is working, you can run simple applications - THSensorApp and SSMTesterApp
+
+4.1 To initiate THSensorApp, please enter as following; 
+
++------------------------------------------------------------------------+
+|~/oic/service/soft-sensor-manager/build/linux/release$ ./THSensorApp    |           
+|~/oic/service/soft-sensor-manager/build/linux/release$ ./THSensorApp1   |                 
++------------------------------------------------------------------------+
+4.2 To initiate SSMTesterApp, please enter as following;
+
++--------------------------------------------------------------------------+
+|~/oic/service/soft-sensor-manager/build/linux/release$ ./SSMTesterApp     |
++--------------------------------------------------------------------------+
+
+Note that the sequence of process initiations should be followed due to the process dependencies.
+
+
+=======================================
+5. Build with SCons
+=======================================
+
+If you want to use Scons to build soft-sensor-manager, build the source code and execute sample applications as following steps.
+
+5.1 After downloading the source codes, type "scons" at project root directory "oic/"
+
++---------------------------------------+
+|~/oic$ scons                           |
++---------------------------------------+
+
+5.2 To execute Soft Sensor Manager and its applications, some shared libraries must be exported.
+
+5.2.1 Go to "oic/out/<target_os>/<target_arch>/release", and check if there are following .so files
+ liboc.so
+ liboctbstack.so
+ liboc_logger.so
+5.2.2 To export the shared libraries, please enter as following;
+
++---------------------------------------------------------------------------------------------------------------------------+
+|~/oic/out/<target_os>/<target_arch>/release$ export LD_LIBRARY_PATH=~/oic/out/<target_os>/<target_arch>/release            |
++---------------------------------------------------------------------------------------------------------------------------+
+
+5.3 Generated outputs from building soft-sensor-manager will be in "oic/out/<target_os>/<target_arch>/release/service/soft-sensor-manager".
+
+5.4 To initiate THSensorApp, please enter as following;
+
++------------------------------------------------------------------------------------------+
+|~/oic/out/<target_os>/<target_arch>/release/service/soft-sensor-manager$ ./THSensorApp    |           
+|~/oic/out/<target_os>/<target_arch>/release/service/soft-sensor-manager$ ./THSensorApp1   |                 
++------------------------------------------------------------------------------------------+
+
+5.5 To initiate SSMTesterApp, please enter as following;
+
++--------------------------------------------------------------------------------------------+
+|~/oic/out/<target_os>/<target_arch>/release/service/soft-sensor-manager$ ./SSMTesterApp     |
++--------------------------------------------------------------------------------------------+
\ No newline at end of file
index c7416e0..687b690 100644 (file)
@@ -30,10 +30,10 @@ if target_os not in ['windows', 'winrt']:
 sdk_env = soft_sensor_manager_env.Clone()
 sdk_env.AppendUnique(CPPPATH = ['SSMCore/include'])
 sdk_env.AppendUnique(CPPPATH = ['SSMCore/src'])
-sdk_env.AppendUnique(CPPPATH = ['SDK/include'])
+sdk_env.AppendUnique(CPPPATH = ['SDK/cpp/include'])
 
 ssm_sdk_cpp_src = [
-               Glob('SDK/src/*.cpp')
+               Glob('SDK/cpp/src/*.cpp')
                ]
 
 env.AppendTarget('libSSMSDK')
@@ -104,4 +104,13 @@ ssmcore_env.InstallTarget(libssmcore, 'libSSMCORE')
 #######################################################################
 ## build SampleApp
 #######################################################################
-SConscript('SampleApp/SConscript')
\ No newline at end of file
+SConscript('SampleApp/SConscript')
+
+
+######################################################################
+# Copy description xml and deliverables
+######################################################################
+Command("SSMTesterApp","SampleApp/linux/SSMTesterApp/SSMTesterApp", Copy("$TARGET", "$SOURCE"))
+Command("SoftSensorDescription.xml", "SoftSensorPlugin/SoftSensorDescription.xml", Copy("$TARGET", "$SOURCE"))
+Command("THSensorApp","SampleApp/linux/THSensorApp/THSensorApp", Copy("$TARGET", "$SOURCE"))
+Command("THSensorApp1","SampleApp/linux/THSensorApp1/THSensorApp1", Copy("$TARGET", "$SOURCE"))
\ No newline at end of file
@@ -1,5 +1,5 @@
--include ../../../build/linux/root_path.inc
--include ../../../build/linux/environment.mk
+-include ../../../../build/linux/root_path.inc
+-include ../../../../build/linux/environment.mk
 
 BOOST=${BOOST_BASE}
 SRC_PATH=../../src
@@ -13,7 +13,7 @@ TARGET=${SSM_LIB}
 
 CXX=g++
 CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX
-CXX_INC=-I../../ -I${INC_PATH}/ -I${FD_SSMCORE}/include -I${FD_SSMCORE}/src -I${IOT_BASE}/include/ -I${IOT_LOG_DIR}/include -I${IOT_BASE}/csdk/stack/include -I${IOT_BASE}/csdk/ocsocket/include -I${IOT_BASE}/csdk/ocrandom/include -I${IOT_BASE}/csdk/logger/include -I${BOOST}
+CXX_INC=-I../../ -I${INC_PATH}/ -I${FD_SSMCORE}/include -I${FD_SSMCORE}/src -I${BOOST}
 CXX_LIB= 
 
 SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
diff --git a/service/soft-sensor-manager/SDK/cpp/include/SSMInterface.h b/service/soft-sensor-manager/SDK/cpp/include/SSMInterface.h
new file mode 100644 (file)
index 0000000..0085b3b
--- /dev/null
@@ -0,0 +1,229 @@
+#ifndef _SSMInterface_H_
+#define _SSMInterface_H_
+
+#include <string>
+#include <vector>
+
+namespace OIC
+{
+    enum SSMRESULT
+    {
+        SSM_S_OK
+        , SSM_S_FALSE
+        , SSM_E_POINTER
+        , SSM_E_OUTOFMEMORY
+        , SSM_E_FAIL
+        , SSM_E_NOINTERFACE
+        , SSM_E_NOTIMPL
+    };
+
+    /**
+    * @class    IModelData
+    * @brief    This class represents context model data package
+    *
+    * @see
+    */
+    class IModelData
+    {
+        public:
+            /**
+            * @fn     getDataId
+            * @brief Get affected DataId. ContextModel has plenty of data so \n
+            *         returned data is matched from given condition
+            *
+            * @param None
+            *
+            * @return int
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual int getDataId() = 0;
+
+            /**
+            * @fn     GetPropertyCount
+            * @brief ContextModel has at least one property that contains data \n
+            *         property is described from its specification.
+            *
+            * @param None
+            *
+            * @return int
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual int getPropertyCount() = 0;
+
+            /**
+            * @fn     getPropertyName
+            * @brief Retrieve propertyName
+            *
+            * @param [in] int propertyIndex - index of property to read
+            *
+            * @return std::string
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual std::string getPropertyName(int propertyIndex) = 0;
+
+            /**
+            * @fn     getPropertyValue
+            * @brief Retrieve propertyValue
+            *
+            * @param [in] int propertyIndex - index of property to read
+            *
+            * @return std::string
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual std::string getPropertyValue(int propertyIndex) = 0;
+
+            /**
+            * @fn     getPropertyValueByName
+            * @brief Retrieve propertyValue using given name
+            *
+            * @param [in] std::string propertyName - property name looking for
+            *
+            * @return std::string
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual std::string getPropertyValueByName(std::string propertyName) = 0;
+        protected:
+            virtual ~IModelData() {};
+    };
+
+    /**
+    * @class    IDataReader
+    * @brief    This class represents context model data package's reader
+    *
+    * @see
+    */
+    class IDataReader
+    {
+        public:
+            /**
+            * @fn     getAffectedModels
+            * @brief Get affected ContextModels. The CQL can specify multiple ContextModels for retrieving data.
+            *
+            * @param [in, out] std::vector<std::string> *pAffectedModels - affected ContextModel list
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT getAffectedModels(std::vector<std::string> *pAffectedModels) = 0;
+
+            /**
+            * @fn     getModelDataCount
+            * @brief Get affected data count. There are multiple data can exist from given condition.
+            *
+            * @param [in] std::string modelName - affected ContextModel name
+            *
+            * @param [in, out] int *pDataCount - affected dataId count
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT getModelDataCount(std::string modelName, int *pDataCount) = 0;
+
+            /**
+            * @fn     getModelData
+            * @brief Get actual Context Model data
+            *
+            * @param [in] std::string modelName - affected ContextModel name
+            *
+            *
+            * @param [in] int dataIndex - affected dataId index
+            *
+            *
+            * @param [out] IModelData **ppModelData - affected ContextModel data reader
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT getModelData(std::string modelName, int dataIndex, IModelData **ppModelData) = 0;
+        protected:
+            virtual ~IDataReader() {};
+    };
+
+    /**
+    * @class    IQueryEngineEvent
+    * @brief    This class represents Query Engine's event that contains results
+    *
+    * @see
+    */
+    class IQueryEngineEvent
+    {
+        public:
+            /**
+            * @fn     onQueryEngineEvent
+            * @brief Transmit result of SSMCore to Application layer
+            *
+            * @param [in] int cqid - entered ContextQuery ID
+            *
+            * @param [in] IDataReader *pResult - result of SSMCore
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult) = 0;
+        protected:
+            virtual ~IQueryEngineEvent() {};
+    };
+
+    /**
+    * @class    SSMInterface
+    * @brief    This class represents main class for querying Soft Sensors
+    *
+    * @see
+    */
+    class SSMInterface
+    {
+        public:
+            SSMInterface();
+            ~SSMInterface();
+
+            /**
+            * @fn     registerQuery
+            * @brief Execute ContextQuery and return ContextQuery ID
+            *
+            * @param [in] std::string queryString - query for requesting data
+            *
+            * @param [in] IQueryEngineEvent listener - listener for receiving data related to query
+            *
+            * @param [in, out] int &cqid - ID of ContextQuery
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            SSMRESULT registerQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
+
+            /**
+            * @fn    unregisterQuery
+            * @brief unregister registered ContextQuery according to cqid
+            *
+            * @param [in] int cqid - Context query corresponding to the cqid will be terminated
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            SSMRESULT unregisterQuery(int cqid);
+    };
+
+}
+#endif
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SDK/include/ISSMClientListener.h b/service/soft-sensor-manager/SDK/include/ISSMClientListener.h
deleted file mode 100644 (file)
index 0eca527..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/******************************************************************
- *
- * Copyright 2014 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.
- *
- ******************************************************************/
-
-/**
- * @file    ISSMClientListener.h
- * @brief   This file contains client listener interfaces.
- */
-
-#ifndef ISSMCLIENTLISTENER_H_
-#define ISSMCLIENTLISTENER_H_
-#include <string>
-#include "OCPlatform.h"
-
-/**
- * @brief This enum defines Soft Sensor return types
- */
-typedef enum
-{
-    SSM_SUCCESS, SSM_ERROR, SSM_ERROR_QUERY_PARSING, SSM_ERROR_NO_QUERY, SSM_ERROR_NETWORK
-} SSMReturn;
-
-using namespace OC;
-/**
- *  @brief  ISSMClientListener is a listener interface from which application is derived to get callback from SoftSensorManager service
- */
-class ISSMClientListener
-{
-    public:
-        /**
-         * @brief   onRegisterQuery is a pure virtual operation which should be implemented in applications to get callback messages.
-         * @param [in] jsonData - A data map in which SoftSensorManager service sends sensor data with cqid.
-         * @param [in] eCode - The address of listener class.  When an application which inherits the ISSMClientListener calls this operation, it sends its address for the listener so that
-         *                          SSMClient can callback message to the appication.
-         * @param [out] cqid - A query id generated from SoftSensorManager service for the queryString request.
-         * @return  SSMReturn
-
-         */
-        virtual void onRegisterQuery(const std::string &jsonData, SSMReturn &eCode) = 0;
-        virtual ~ISSMClientListener()
-        {
-        }
-};
-
-#endif /* ISSMCLIENTLISTENER_H_ */
diff --git a/service/soft-sensor-manager/SDK/include/SSMClient.h b/service/soft-sensor-manager/SDK/include/SSMClient.h
deleted file mode 100644 (file)
index dd9d899..0000000
+++ /dev/null
@@ -1,247 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/**
- * @file    SSMClient.h
- * @brief   This file contains the declaration of classes and its members related to SSMClient.
- */
-
-#ifndef RESOURCECLIENT_H_
-#define RESOURCECLIENT_H_
-
-#include <string>
-
-#include "OCResource.h"
-#include "OCPlatform.h"
-#include "ISSMClientListener.h"
-
-using namespace OC;
-
-#if defined(WIN32)
-class CSemaphore
-{
-    private:
-        HANDLE hSemaphore;
-        int m_MaxTimeOut;
-
-    public:
-        /**
-         * This is CSemaphore constructor.
-         */
-        CSemaphore()
-        {
-            m_MaxTimeOut = 0;
-        }
-        /**
-         *This is CSemaphore destructor.
-         */
-        ~CSemaphore()
-        {
-        }
-
-        /**
-         * This is a function to creat a semaphore
-         * This is syncronus call.
-         * @param maximumRequestTimeOut
-         *          [IN] Request Time out.
-         *
-         * @return  None
-         *
-         */
-        void create(int maximumRequestTimeOut)
-        {
-            hSemaphore = CreateSemaphore(NULL, 1, 1, NULL);
-            m_MaxTimeOut = maximumRequestTimeOut;
-        }
-
-        /**
-         * This is a function to wait for semaphore
-         *
-         * @return  None
-         *
-         */
-        void wait()
-        {
-            WaitForSingleObject(hSemaphore, m_MaxTimeOut);
-        }
-
-        /**
-         * This is a function to release  semaphore
-         *
-         * @return  None
-         *
-         */
-        void release()
-        {
-            ReleaseSemaphore(hSemaphore, 1, NULL);
-        }
-
-};
-
-#elif defined(LINUX)
-#include <semaphore.h>
-
-#define SEM_SUCCESS     0
-
-class CSemaphore
-{
-    private:
-        sem_t hSemaphore;
-        timespec m_MaxTimeOut;
-
-    public:
-        /**
-         * This is CSemaphore constructor.
-         */
-        CSemaphore()
-        {
-            m_MaxTimeOut.tv_sec = 0;
-            m_MaxTimeOut.tv_nsec = 0;
-        }
-        /**
-         *This is CSemaphore destructor.
-         */
-        ~CSemaphore()
-        {
-        }
-        /**
-         * This is a function to creat a semaphore
-         * This is syncronus call.
-         * @param maximumRequestTimeOut
-         *          [IN] Request Time out.
-         *
-         * @return  None
-         *
-         */
-        void create(int maximumRequestTimeOut)
-        {
-            if ( sem_init(&hSemaphore, 1, 0) < SEM_SUCCESS )
-            {
-                perror("Error : sem_init.");
-                exit(0);
-            }
-            m_MaxTimeOut.tv_sec = maximumRequestTimeOut;
-        }
-
-        void wait()
-        {
-            sem_wait( &hSemaphore );
-        }
-
-        /**
-         * This is a function to release  semaphore
-         *
-         * @return  None
-         *
-         */
-        void release()
-        {
-            sem_post(&hSemaphore);
-        }
-
-};
-#endif
-
-/**
- *  @brief  SSMClient is a wrapper class to provide SoftSensorManager functionality to Application.
- *          Basically, SoftSensorManager is developed in Resource model (i.e. messaging with basic functions of put, get, and post).
- *          SSMClient abstracts the resource based operations from client applications and provides c++ style functions.
- */
-class SSMClient
-{
-    private:
-        SSMReturn m_retResponse;
-        CSemaphore m_sem;
-        /**
-         * @brief SoftSensorManager Resource.
-         */
-        std::shared_ptr< OCResource > m_SSMResource;
-        /**
-         * @brief attribute map .
-         */
-        std::map<std::string, std::string> m_responseAttributeMap;
-        /**
-         * @brief query engine.
-         */
-        std::string m_queryEngineId;
-        /**
-         * @brief app listener
-         */
-        ISSMClientListener *m_appListener;
-
-        /**
-         * @brief internal find resource function
-         */
-        void _findResource(void);
-
-        /**
-         * @brief internal Query engine function
-         */
-        void _createQueryEngine(void);
-
-        /**
-         * @brief internal release query function
-         */
-        void _releaseQueryEngine(std::string queryEngineId);
-
-    public:
-        /**
-         * Constructor for SSMClient.
-         */
-        SSMClient();
-        ~SSMClient();
-
-        /**
-         * This API sends query strings of applications to SoftSensorManager on Iotivity Base messaging.
-         *
-         * @param [in] queryString - A conditions query statement where the caller application specifies sensors for required data and conditions when the caller wants to get the data.
-         * @param [in] listener - The address of listener class.  When an application which inherits the ISSMClientListener calls this operation, it sends its address for the listener so that
-         *                          SSMClient can callback message to the application.
-         * @param [out] cqid - A query id generated from SoftSensorManager service for the queryString request.
-         * @return  SSMReturn
-
-         */
-        SSMReturn registerQuery(std::string queryString, ISSMClientListener *listener,
-                                std::string &cqid);
-        /**
-         * This API is to cancel the registered sends query strings of applications to SoftSensorManager on Iotivity Base messaging.
-         *
-         * @param [in] listener - The address of listener class.  When an application which inherits the ISSMClientListener calls this operation, it sends its address for the listener so that
-         *                          SSMClient can callback message to the application.
-         * @param [in] cqid - A query id generated from SoftSensorManager service for the queryString request.
-         * @return  SSMReturn
-         */
-        SSMReturn unregisterQuery(std::string cqid);
-
-        // friend option. for callback from SSMResource
-        void onFoundResource(std::shared_ptr< OCResource > resource);
-        void onCreateQueryEngine(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                                 const int eCode);
-        void onReleaseQueryEngine(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                                  const int eCode);
-        void onRegisterQuery(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                             const int eCode);
-        void onUnregisterQuery(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                               const int eCode);
-        void onObserve(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int &eCode,
-                       const int &sequenceNumber);
-};
-
-#endif /* RESOURCECLIENT_H_ */
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/CoreController.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/CoreController.java
new file mode 100644 (file)
index 0000000..38ff87c
--- /dev/null
@@ -0,0 +1,74 @@
+package org.iotivity.service.ssm;
+
+import java.util.List;
+
+import android.util.Log;
+
+public class CoreController 
+{
+       static
+       {
+               try
+               {
+                       String workingPath = System.getProperty( "user.dir" );
+                       
+                       Log.i("SSMTester", "loading ssm lib");
+                       
+                       // for android: not complete method
+                       if(System.getProperty("os.name").toLowerCase().equals("linux"))
+                       {
+                               //System.out.println("System load Android library");
+                               System.loadLibrary("SSMCore_Android");
+                       }
+                       else
+                       {
+                               //System.out.println("System load 32bit library");
+                               workingPath += "/../Outputs/";
+                               System.load( workingPath + "SSMCore_Windows.dll");
+                       }
+                       
+                       Log.i("SSMTester", "loading done");
+               }
+               catch(UnsatisfiedLinkError e)
+               {
+                       System.out.println(e.getMessage());
+               }
+       }
+       
+       static private CoreController coreController;
+       
+       public static CoreController getInstance()
+       {
+               if(coreController == null)
+                       coreController = new CoreController();
+               
+               return coreController;
+       }
+       
+       public native void InitializeSSMCore(String xmlDescription);
+       public native void StartSSMCore();
+       public native void StopSSMCore();
+       public native void TerminateSSMCore();
+       public native QueryEngine CreateQueryEngine();
+       public native int ReleaseQueryEngine(QueryEngine queryEngine);
+       
+       // QueryEngine
+       public native int ExecuteContextQuery(int pQueryEngineInstance, String contextQuery);
+       public native void RegisterQueryEvent(int pQueryEngineInstance, IQueryEngineEvent queryEngineEvent);
+       public native void KillContextQuery(int pQueryEngineInstance, int cqid);        
+               
+       //public native void UnregiterQueryEvent(int pQueryEngineInstance, IQueryEngineEvent queryEngineEvent);
+
+       //IModelData
+       public native int GetDataId(int pIModelDataInstance);   
+       public native int GetPropertyCount(int pIModelDataInstance);
+       public native String GetPropertyName(int pIModelDataInstance, int propertyIndex);
+       public native String GetPropertyValue(int pIModelDataInstance, int propertyIndex);
+               
+       //IDataReader
+       public native List<String> GetAffectedModels(int pDataReaderInstance);
+       public native int GetModelDataCount(int pDataReaderInstance, String modelName);
+       public native ModelData GetModelData(int pDataReaderInstance, String modelName, int dataIndex);
+       
+       public native void RegisterReportReceiver(IReportReceiver reportReceiver);
+}
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/DataReader.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/DataReader.java
new file mode 100644 (file)
index 0000000..c963a25
--- /dev/null
@@ -0,0 +1,28 @@
+package org.iotivity.service.ssm;
+
+import java.util.List;
+
+public class DataReader {
+
+       private int pDataReaderInstance;
+       
+       public DataReader(int dataReaderInstance)
+       {
+               pDataReaderInstance = dataReaderInstance;
+       }
+       
+       public List<String> GetAffectedModels()
+       {
+               return CoreController.getInstance().GetAffectedModels(pDataReaderInstance);
+       }
+       
+       public int GetModelDataCount(String modelName)
+       {
+               return CoreController.getInstance().GetModelDataCount(pDataReaderInstance, modelName);
+       }
+       
+       public ModelData GetModelData(String modelName, int dataIndex)
+       {
+               return CoreController.getInstance().GetModelData(pDataReaderInstance, modelName, dataIndex);
+       }
+}
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IQueryEngineEvent.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IQueryEngineEvent.java
new file mode 100644 (file)
index 0000000..3dd46bf
--- /dev/null
@@ -0,0 +1,5 @@
+package org.iotivity.service.ssm;
+
+public interface IQueryEngineEvent {
+       public void OnQueryEngineEvent(int cqid, DataReader result);
+}
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IReportReceiver.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/IReportReceiver.java
new file mode 100644 (file)
index 0000000..9a8aec1
--- /dev/null
@@ -0,0 +1,5 @@
+package org.iotivity.service.ssm;
+
+public interface IReportReceiver {
+       public void OnMessageReceived(String tag, String msg);
+}
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/ModelData.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/ModelData.java
new file mode 100644 (file)
index 0000000..c43e1df
--- /dev/null
@@ -0,0 +1,31 @@
+package org.iotivity.service.ssm;
+
+public class ModelData {
+       
+       private int pIModelDataInstance;
+       
+       public ModelData(int iModelDataInstance)
+       {
+               pIModelDataInstance = iModelDataInstance;
+       }
+       
+       public int GetDataId()
+       {
+               return CoreController.getInstance().GetDataId(pIModelDataInstance);
+       }
+       
+       public int GetPropertyCount()
+       {
+               return CoreController.getInstance().GetPropertyCount(pIModelDataInstance);
+       }
+       
+       public String GetPropertyName(int propertyIndex)
+       {
+               return CoreController.getInstance().GetPropertyName(pIModelDataInstance, propertyIndex);
+       }
+       
+       public String GetPropertyValue(int propertyIndex)
+       {
+               return CoreController.getInstance().GetPropertyValue(pIModelDataInstance, propertyIndex);
+       }
+}
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/QueryEngine.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/QueryEngine.java
new file mode 100644 (file)
index 0000000..a14e640
--- /dev/null
@@ -0,0 +1,31 @@
+package org.iotivity.service.ssm;
+
+public class QueryEngine
+{
+       private int pQueryEngineInstance;
+       
+       public QueryEngine(int queryEngineInstance)
+       {
+               pQueryEngineInstance = queryEngineInstance;
+       }
+       
+       public int GetQueryEngineInstance()
+       {
+               return pQueryEngineInstance;
+       }
+       
+       public int ExecuteContextQuery(String contextQuery)
+       {
+               return CoreController.getInstance().ExecuteContextQuery(pQueryEngineInstance, contextQuery);
+       }
+       
+       public void RegisterQueryEvent(IQueryEngineEvent queryEngineEvent)
+       {
+               CoreController.getInstance().RegisterQueryEvent(pQueryEngineInstance, queryEngineEvent);
+       }
+       
+       public void KillContextQuery(int cqid)
+       {
+               CoreController.getInstance().KillContextQuery(pQueryEngineInstance, cqid);
+       }
+}
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/SSMInterface.java b/service/soft-sensor-manager/SDK/java/org/iotivity/service/ssm/SSMInterface.java
new file mode 100644 (file)
index 0000000..8169548
--- /dev/null
@@ -0,0 +1,99 @@
+package org.iotivity.service.ssm;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+public class SSMInterface {
+       private class QueryEngineEventReceiver implements IQueryEngineEvent
+       {
+        private Lock                                                           mMtxListener = new ReentrantLock();
+               private Map<Integer, IQueryEngineEvent>         mMapListener = new HashMap<Integer, IQueryEngineEvent>();
+               
+               public void OnQueryEngineEvent(int cqid, DataReader result)
+               {
+                       mMtxListener.lock();
+
+                       mMapListener.get(cqid).OnQueryEngineEvent(cqid, result);
+            
+                       mMtxListener.unlock();
+               }
+               void lockListener()
+        {
+                       mMtxListener.lock();
+        }
+
+        void unlockListener()
+        {
+               mMtxListener.unlock();
+        }
+
+        void addListener(int cqid, IQueryEngineEvent engineEvent)
+        {
+               mMapListener.put(cqid, engineEvent);
+        }
+
+        void removeListener(int cqid)
+        {
+               mMapListener.remove(cqid);
+        }
+       };
+       
+       private CoreController                          mSSMCore = null;
+       private QueryEngine                                     mQueryEngine = null;
+       private QueryEngineEventReceiver        mQueryEngineEventListenerReceiver = new QueryEngineEventReceiver();
+       private List<Integer>                           mRunningCQLs = new ArrayList<Integer>();
+       
+       public SSMInterface()
+       {               
+       }
+       
+       public void startSSMCore(String initConfig) throws Exception
+       {
+               mSSMCore = CoreController.getInstance();
+        mSSMCore.InitializeSSMCore(initConfig);
+        mSSMCore.StartSSMCore();
+        
+        mQueryEngine = mSSMCore.CreateQueryEngine();
+        
+        if(mQueryEngine == null)
+               throw new Exception("Create Query Engine failed");
+        
+        mQueryEngine.RegisterQueryEvent(mQueryEngineEventListenerReceiver);
+       }
+       
+       public void stopSSMCore()
+       {
+               mQueryEngine.RegisterQueryEvent(null);
+               mSSMCore.ReleaseQueryEngine(mQueryEngine);
+               mQueryEngineEventListenerReceiver = null;
+               mQueryEngine = null;
+               mSSMCore.StopSSMCore();
+               mSSMCore.TerminateSSMCore();
+       }
+       
+       public int registerQuery(String contextQuery, IQueryEngineEvent listener)
+       {
+               int cqid;
+               
+               mQueryEngineEventListenerReceiver.lockListener();
+               cqid = mQueryEngine.ExecuteContextQuery(contextQuery);
+               mQueryEngineEventListenerReceiver.addListener(cqid, listener);
+               mRunningCQLs.add(cqid);
+               mQueryEngineEventListenerReceiver.unlockListener();
+               
+               return cqid;
+       }
+       
+       public void unregisterQuery(int cqid)
+       {
+               mQueryEngineEventListenerReceiver.lockListener();
+               mQueryEngine.KillContextQuery(cqid);
+               mQueryEngineEventListenerReceiver.removeListener(cqid);
+               mRunningCQLs.remove(cqid);
+               mQueryEngineEventListenerReceiver.unlockListener();
+       }
+}
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SDK/src/SSMClient.cpp b/service/soft-sensor-manager/SDK/src/SSMClient.cpp
deleted file mode 100644 (file)
index 572e513..0000000
+++ /dev/null
@@ -1,284 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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 <iostream>
-#include <string>
-
-#include "SSMClient.h"
-#include "OCPlatform.h"
-#include "OCApi.h"
-
-const char *SSM_RESOURCE_URI = "/service/SoftSensorManager";
-
-#define SSM_RESOURCE_TYPE       = "core.SoftSensorManager"
-
-#define COAP_SERVER_ADDR        "coap://224.0.1.187/oc/core?rt=core.SoftSensorManager"
-
-SSMClient::SSMClient()
-{
-    m_sem.create(100000);
-    m_appListener = NULL;
-    m_retResponse = SSM_ERROR;
-    _findResource();
-    _createQueryEngine();
-}
-
-SSMClient::~SSMClient()
-{
-    _releaseQueryEngine(m_queryEngineId);
-}
-
-void SSMClient::_findResource()
-{
-    // Create PlatformConfig object
-    PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both,
-                       "0.0.0.0", 0, OC::QualityOfService::LowQos);
-
-    // Create a OCPlatform instance.
-    // Note: Platform creation is synchronous call.
-    try
-    {
-        OCPlatform::Configure(cfg);
-
-        // Find all resources
-        OCStackResult result;
-        if ((result = OCPlatform::findResource("", COAP_SERVER_ADDR,
-                                               std::bind(&SSMClient::onFoundResource, this, std::placeholders::_1)))
-            != OC_STACK_OK)
-        {
-            std::cout << "Faile to Find Resource... " << std::endl;
-            return;
-        }
-        std::cout << "Find Resource... " << std::endl;
-
-        m_sem.wait();
-
-    }
-    catch (OCException e)
-    {
-        //log(e.what());
-    }
-}
-
-void SSMClient::_createQueryEngine(void)
-{
-    OCRepresentation rep;
-
-    QueryParamsMap queryParamsMap;
-
-    rep.setValue("command", std::string("CreateQueryEngine"));
-
-    if (m_SSMResource->put(rep, queryParamsMap,
-                           std::bind(&SSMClient::onCreateQueryEngine, this, std::placeholders::_1,
-                                     std::placeholders::_2, std::placeholders::_3)) != OC_STACK_OK)
-    {
-        return;
-    }
-
-    m_sem.wait();
-}
-
-void SSMClient::_releaseQueryEngine(std::string queryEngineId)
-{
-    OCRepresentation rep;
-
-    QueryParamsMap queryParamsMap;
-
-    rep.setValue("command", std::string("ReleaseQueryEngine"));
-    rep.setValue("queryEngineId", queryEngineId);
-
-    m_SSMResource->put(rep, queryParamsMap,
-                       std::bind(&SSMClient::onReleaseQueryEngine, this, std::placeholders::_1,
-                                 std::placeholders::_2, std::placeholders::_3));
-
-    m_sem.wait();
-}
-
-SSMReturn SSMClient::registerQuery(std::string queryString, ISSMClientListener *listener,
-                                   std::string &cqid)
-{
-    OCRepresentation rep;
-
-    QueryParamsMap queryParamsMap;
-
-
-    rep.setValue("command", std::string("ExecuteContextQuery"));
-    rep.setValue("queryEngineId", m_queryEngineId);
-    rep.setValue("contextQuery", queryString);
-
-    m_appListener = listener;
-
-    if (m_SSMResource->put(rep, queryParamsMap,
-                           std::bind(&SSMClient::onRegisterQuery, this, std::placeholders::_1,
-                                     std::placeholders::_2, std::placeholders::_3)) != OC_STACK_OK)
-        return SSM_ERROR_NETWORK;
-
-    m_sem.wait();
-
-    if (m_retResponse == SSM_SUCCESS)
-    {
-        cqid = m_responseAttributeMap["CQID"];
-    }
-
-    return m_retResponse;
-}
-
-SSMReturn SSMClient::unregisterQuery(std::string cqid)
-{
-    OCRepresentation rep;
-
-    QueryParamsMap queryParamsMap;
-
-    rep.setValue("command", std::string("KillContextQuery"));
-    rep.setValue("queryEngineId", m_queryEngineId);
-    rep.setValue("CQID", cqid);
-
-    if (m_SSMResource->put(rep, queryParamsMap,
-                           std::bind(&SSMClient::onUnregisterQuery, this, std::placeholders::_1,
-                                     std::placeholders::_2, std::placeholders::_3)) != OC_STACK_OK)
-        return SSM_ERROR_NETWORK;
-
-    m_sem.wait();
-
-    return m_retResponse;
-}
-
-/**
- * Callback Function List.
- */
-// Callback to found resources
-void SSMClient::onFoundResource(std::shared_ptr< OCResource > resource)
-{
-    std::string resourceURI;
-    try
-    {
-        // Do some operations with resource object.
-        if (resource)
-        {
-            // Get the resource URI
-            resourceURI = resource->uri();
-
-            if (resourceURI.compare(SSM_RESOURCE_URI) == 0)
-            {
-                m_SSMResource = resource;
-            }
-        }
-    }
-    catch (std::exception &e)
-    {
-        //log(e.what());
-    }
-
-    m_sem.release();
-}
-
-void SSMClient::onCreateQueryEngine(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                                    const int eCode)
-{
-    if (eCode != 0)
-    {
-        m_retResponse = SSM_ERROR_NETWORK;
-        goto CLEANUP;
-    }
-
-    m_queryEngineId = rep.getValue<std::string>("queryEngineId");
-    m_retResponse = SSM_SUCCESS;
-
-CLEANUP: m_sem.release();
-}
-
-void SSMClient::onRegisterQuery(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                                const int eCode)
-{
-    QueryParamsMap queryParamsMap;
-
-    if (eCode != 0)
-    {
-        m_retResponse = SSM_ERROR_NETWORK;
-        goto CLEANUP;
-    }
-
-    if (rep.hasAttribute("error"))
-    {
-        m_retResponse = SSM_ERROR_QUERY_PARSING;
-        goto CLEANUP;
-    }
-
-    m_SSMResource->observe(ObserveType::Observe, queryParamsMap,
-                           std::bind(&SSMClient::onObserve, this, std::placeholders::_1,
-                                     std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
-
-    m_responseAttributeMap.clear();
-
-    m_responseAttributeMap["CQID"] = rep.getValue<std::string>("CQID");
-
-    m_retResponse = SSM_SUCCESS;
-
-CLEANUP: m_sem.release();
-}
-
-void SSMClient::onUnregisterQuery(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                                  const int eCode)
-{
-    if (eCode != 0)
-    {
-        m_retResponse = SSM_ERROR_NETWORK;
-        goto CLEANUP;
-    }
-
-    if (rep.hasAttribute("error"))
-    {
-        m_retResponse = SSM_ERROR_NO_QUERY;
-        goto CLEANUP;
-    }
-
-    m_responseAttributeMap.clear();
-
-    m_retResponse = SSM_SUCCESS;
-
-CLEANUP: m_sem.release();
-}
-
-void SSMClient::onReleaseQueryEngine(const HeaderOptions &headerOptions,
-                                     const OCRepresentation &rep, const int eCode)
-{
-    if (eCode != 0)
-    {
-        m_retResponse = SSM_ERROR_NETWORK;
-        goto CLEANUP;
-    }
-
-    m_retResponse = SSM_SUCCESS;
-
-CLEANUP: m_sem.release();
-}
-
-void SSMClient::onObserve(const HeaderOptions &headerOptions, const OCRepresentation &rep,
-                          const int &eCode, const int &sequenceNumber)
-{
-    SSMReturn ret = SSM_SUCCESS;
-
-    if (eCode != 0)
-    {
-        ret = SSM_ERROR_NETWORK;
-    }
-
-    m_appListener->onRegisterQuery(rep.getJSONRepresentation(), ret);
-}
index f6a3f19..01d6453 100644 (file)
@@ -69,6 +69,7 @@ ${TARGET}: ${GCC_OBJLIST} ${CXX_OBJLIST}
 
 post_job:
        @echo " " 
+       cp -Rdp ${INC_PATH}/SSMInterface.h ${FD_SDK}/include/
        cp -Rdp ./${RST_NAME}/${TARGET} ${OUTPUTS_DIR}/
        cp -Rdp ${INC_PATH}/SSMInterface.h ${OUTPUTS_DIR}/
        cp -Rdp ${SRC_PATH}/SSMInterface/SSMModelDefinition.h ${OUTPUTS_DIR}/
index b126130..0085b3b 100644 (file)
 #include <string>
 #include <vector>
 
-enum SSMRESULT
+namespace OIC
 {
-    SSM_S_OK
-    , SSM_S_FALSE
-    , SSM_E_POINTER
-    , SSM_E_OUTOFMEMORY
-    , SSM_E_FAIL
-    , SSM_E_NOINTERFACE
-    , SSM_E_NOTIMPL
-};
+    enum SSMRESULT
+    {
+        SSM_S_OK
+        , SSM_S_FALSE
+        , SSM_E_POINTER
+        , SSM_E_OUTOFMEMORY
+        , SSM_E_FAIL
+        , SSM_E_NOINTERFACE
+        , SSM_E_NOTIMPL
+    };
 
-/**
-* @class    IModelData
-* @brief    IModelData Interface
-*            This class represents context model data package
-*
-* @see
-*/
-class IModelData
-{
-    public:
-        /**
-        * @fn     getDataId
-        * @brief Get affected DataId. ContextModel has plenty of data so \n
-        *         returned data is matched from given condition
-        *
-        * @param None
-        *
-        * @return int
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual int getDataId() = 0;
+    /**
+    * @class    IModelData
+    * @brief    This class represents context model data package
+    *
+    * @see
+    */
+    class IModelData
+    {
+        public:
+            /**
+            * @fn     getDataId
+            * @brief Get affected DataId. ContextModel has plenty of data so \n
+            *         returned data is matched from given condition
+            *
+            * @param None
+            *
+            * @return int
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual int getDataId() = 0;
 
-        /**
-        * @fn     GetPropertyCount
-        * @brief ContextModel has at least one property that contains data \n
-        *         property is described from its specification.
-        *
-        * @param None
-        *
-        * @return int
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual int getPropertyCount() = 0;
+            /**
+            * @fn     GetPropertyCount
+            * @brief ContextModel has at least one property that contains data \n
+            *         property is described from its specification.
+            *
+            * @param None
+            *
+            * @return int
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual int getPropertyCount() = 0;
 
-        /**
-        * @fn     getPropertyName
-        * @brief Retrieve propertyName
-        *
-        * @param [in] int propertyIndex - index of property to read
-        *
-        * @return std::string
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual std::string getPropertyName(int propertyIndex) = 0;
+            /**
+            * @fn     getPropertyName
+            * @brief Retrieve propertyName
+            *
+            * @param [in] int propertyIndex - index of property to read
+            *
+            * @return std::string
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual std::string getPropertyName(int propertyIndex) = 0;
 
-        /**
-        * @fn     getPropertyValue
-        * @brief Retrieve propertyValue
-        *
-        * @param [in] int propertyIndex - index of property to read
-        *
-        * @return std::string
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual std::string getPropertyValue(int propertyIndex) = 0;
+            /**
+            * @fn     getPropertyValue
+            * @brief Retrieve propertyValue
+            *
+            * @param [in] int propertyIndex - index of property to read
+            *
+            * @return std::string
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual std::string getPropertyValue(int propertyIndex) = 0;
 
-        /**
-        * @fn     getPropertyValueByName
-        * @brief Retrieve propertyValue using given name
-        *
-        * @param [in] std::string propertyName - property name looking for
-        *
-        * @return std::string
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual std::string getPropertyValueByName(std::string propertyName) = 0;
-    protected:
-        virtual ~IModelData() {};
-};
+            /**
+            * @fn     getPropertyValueByName
+            * @brief Retrieve propertyValue using given name
+            *
+            * @param [in] std::string propertyName - property name looking for
+            *
+            * @return std::string
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual std::string getPropertyValueByName(std::string propertyName) = 0;
+        protected:
+            virtual ~IModelData() {};
+    };
 
-/**
-* @class    IDataReader
-* @brief    IDataReader Interface
-*            This class represents context model data package's reader
-*
-* @see
-*/
-class IDataReader
-{
-    public:
-        /**
-        * @fn     getAffectedModels
-        * @brief Get affected ContextModels. The CQL can specify multiple ContextModels for retrieving data.
-        *
-        * @param [out] std::vector<std::string> *pAffectedModels - affected ContextModel list
-        *
-        * @return SSMRESULT
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual SSMRESULT getAffectedModels(std::vector<std::string> *pAffectedModels) = 0;
+    /**
+    * @class    IDataReader
+    * @brief    This class represents context model data package's reader
+    *
+    * @see
+    */
+    class IDataReader
+    {
+        public:
+            /**
+            * @fn     getAffectedModels
+            * @brief Get affected ContextModels. The CQL can specify multiple ContextModels for retrieving data.
+            *
+            * @param [in, out] std::vector<std::string> *pAffectedModels - affected ContextModel list
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT getAffectedModels(std::vector<std::string> *pAffectedModels) = 0;
 
-        /**
-        * @fn     getModelDataCount
-        * @brief Get affected data count. There are multiple data can exist from given condition.
-        *
-        * @param [in] std::string modelName - affected ContextModel name
-        *
-        * @param [out] int *pDataCount - affected dataId count
-        *
-        * @return SSMRESULT
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual SSMRESULT getModelDataCount(std::string modelName, int *pDataCount) = 0;
+            /**
+            * @fn     getModelDataCount
+            * @brief Get affected data count. There are multiple data can exist from given condition.
+            *
+            * @param [in] std::string modelName - affected ContextModel name
+            *
+            * @param [in, out] int *pDataCount - affected dataId count
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT getModelDataCount(std::string modelName, int *pDataCount) = 0;
 
-        /**
-        * @fn     getModelData
-        * @brief Get actual Context Model data
-        *
-        * @param [in] std::string modelName - affected ContextModel name
-        *
-        *
-        * @param [in] int dataIndex - affected dataId index
-        *
-        *
-        * @param [out] IModelData **ppModelData - affected ContextModel data reader
-        *
-        * @return SSMRESULT
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual SSMRESULT getModelData(std::string modelName, int dataIndex, IModelData **ppModelData) = 0;
-    protected:
-        virtual ~IDataReader() {};
-};
+            /**
+            * @fn     getModelData
+            * @brief Get actual Context Model data
+            *
+            * @param [in] std::string modelName - affected ContextModel name
+            *
+            *
+            * @param [in] int dataIndex - affected dataId index
+            *
+            *
+            * @param [out] IModelData **ppModelData - affected ContextModel data reader
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT getModelData(std::string modelName, int dataIndex, IModelData **ppModelData) = 0;
+        protected:
+            virtual ~IDataReader() {};
+    };
 
-/**
-* @class    IQueryEngineEvent
-* @brief    IQueryEngineEvent Interface
-*            This class represents Query Engine's event that contains results
-*
-* @see
-*/
-class IQueryEngineEvent
-{
-    public:
-        /**
-        * @fn     onQueryEngineEvent
-        * @brief Transmit result of SSMCore to Application layer
-        *
-        * @param [in] int cqid - entered ContextQuery ID
-        *
-        * @param [in] IDataReader *pResult - result of SSMCore
-        *
-        * @return SSMRESULT
-        * @warning
-        * @exception
-        * @see
-        */
-        virtual SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult) = 0;
-    protected:
-        virtual ~IQueryEngineEvent() {};
-};
+    /**
+    * @class    IQueryEngineEvent
+    * @brief    This class represents Query Engine's event that contains results
+    *
+    * @see
+    */
+    class IQueryEngineEvent
+    {
+        public:
+            /**
+            * @fn     onQueryEngineEvent
+            * @brief Transmit result of SSMCore to Application layer
+            *
+            * @param [in] int cqid - entered ContextQuery ID
+            *
+            * @param [in] IDataReader *pResult - result of SSMCore
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            virtual SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult) = 0;
+        protected:
+            virtual ~IQueryEngineEvent() {};
+    };
 
-class SSMInterface
-{
-    public:
-        SSMInterface();
-        ~SSMInterface();
+    /**
+    * @class    SSMInterface
+    * @brief    This class represents main class for querying Soft Sensors
+    *
+    * @see
+    */
+    class SSMInterface
+    {
+        public:
+            SSMInterface();
+            ~SSMInterface();
+
+            /**
+            * @fn     registerQuery
+            * @brief Execute ContextQuery and return ContextQuery ID
+            *
+            * @param [in] std::string queryString - query for requesting data
+            *
+            * @param [in] IQueryEngineEvent listener - listener for receiving data related to query
+            *
+            * @param [in, out] int &cqid - ID of ContextQuery
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            SSMRESULT registerQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
+
+            /**
+            * @fn    unregisterQuery
+            * @brief unregister registered ContextQuery according to cqid
+            *
+            * @param [in] int cqid - Context query corresponding to the cqid will be terminated
+            *
+            * @return SSMRESULT
+            * @warning
+            * @exception
+            * @see
+            */
+            SSMRESULT unregisterQuery(int cqid);
+    };
 
-        SSMRESULT registerQuery(std::string queryString, IQueryEngineEvent *listener, int &cqid);
-        SSMRESULT unregisterQuery(int cqid);
-};
+}
 #endif
\ No newline at end of file
index b2517e7..373734e 100644 (file)
@@ -56,11 +56,17 @@ const OID OID_IBase = {0x3b465976, 0x6486, 0x4c1f, {0x84, 0xb9, 0xeb, 0x80, 0x79
 */
 inline int IsEqualOID(const OID &oid1, const OID &oid2)
 {
-    return (
-               ((unsigned long *) &oid1)[0] == ((unsigned long *) &oid2)[0] &&
-               ((unsigned long *) &oid1)[1] == ((unsigned long *) &oid2)[1] &&
-               ((unsigned long *) &oid1)[2] == ((unsigned long *) &oid2)[2] &&
-               ((unsigned long *) &oid1)[3] == ((unsigned long *) &oid2)[3]);
+    return (( oid1.data1 ==  oid2.data1) &&
+            ( oid1.data2 ==  oid2.data2) &&
+            ( oid1.data3 ==  oid2.data3) &&
+            ( oid1.data4[0] ==  oid2.data4[0]) &&
+            ( oid1.data4[1] ==  oid2.data4[1]) &&
+            ( oid1.data4[2] ==  oid2.data4[2]) &&
+            ( oid1.data4[3] ==  oid2.data4[3]) &&
+            ( oid1.data4[4] ==  oid2.data4[4]) &&
+            ( oid1.data4[5] ==  oid2.data4[5]) &&
+            ( oid1.data4[6] ==  oid2.data4[6]) &&
+            ( oid1.data4[7] ==  oid2.data4[7]));
 }
 
 /**
index 93502c2..20029b1 100644 (file)
@@ -92,7 +92,7 @@ CLEANUP:
 void CContextModel::registerSSMResource(IN ActivationType activationType, IN int targetDeviceDataId,
                                         IN ISSMResource *pSSMResource)
 {
-    int     *pData = NULL;
+    intptr_t     *pData = NULL;
 
     m_mtxActivationCount.lock();
     switch (activationType)
@@ -100,9 +100,9 @@ void CContextModel::registerSSMResource(IN ActivationType activationType, IN int
         case ACTIVATION_TYPE_SUBSCRIBE:
             if (m_mapSubscribedDevice.find(targetDeviceDataId) == m_mapSubscribedDevice.end())
             {
-                pData = new int[2];
+                pData = new intptr_t  [2];
                 pData[0] = STATUS_ACTIVATE;
-                pData[1] = (int)pSSMResource;
+                pData[1] = reinterpret_cast<intptr_t>(pSSMResource);
                 m_pTasker->addTask(this, (void *)pData);
                 m_mapSubscribedDevice[targetDeviceDataId] = 1;
             }
@@ -117,9 +117,9 @@ void CContextModel::registerSSMResource(IN ActivationType activationType, IN int
             {
                 if (m_mapGetDevice.find(targetDeviceDataId) == m_mapGetDevice.end())
                 {
-                    pData = new int[2];
+                    pData = new intptr_t[2];
                     pData[0] = STATUS_START_READ_VALUE;
-                    pData[1] = (int)pSSMResource;
+                    pData[1] = reinterpret_cast<intptr_t>(pSSMResource);
                     m_pTasker->addTask(this, (void *)pData);
                     m_mapGetDevice[targetDeviceDataId] = 1;
                 }
@@ -139,7 +139,7 @@ void CContextModel::registerSSMResource(IN ActivationType activationType, IN int
 void CContextModel::unregisterSSMResource(IN ActivationType activationType,
         IN int targetDeviceDataId, IN ISSMResource *pSSMResource)
 {
-    int     *pData = NULL;
+    intptr_t     *pData = NULL;
 
     m_mtxActivationCount.lock();
     switch (activationType)
@@ -149,9 +149,9 @@ void CContextModel::unregisterSSMResource(IN ActivationType activationType,
             {
                 if (--m_mapSubscribedDevice[targetDeviceDataId] == 0)
                 {
-                    pData = new int[2];
+                    pData = new intptr_t [2];
                     pData[0] = STATUS_DEACTIVATE;
-                    pData[1] = (int)pSSMResource;
+                    pData[1] = reinterpret_cast<intptr_t>(pSSMResource);
                     m_pTasker->addTask(this, (void *)pData);
                     m_mapSubscribedDevice.erase(targetDeviceDataId);
                 }
@@ -163,9 +163,9 @@ void CContextModel::unregisterSSMResource(IN ActivationType activationType,
             {
                 if (--m_mapGetDevice[targetDeviceDataId] == 0)
                 {
-                    pData = new int[2];
+                    pData = new intptr_t [2];
                     pData[0] = STATUS_STOP_READ_VALUE;
-                    pData[1] = (int)pSSMResource;
+                    pData[1] = reinterpret_cast<intptr_t>(pSSMResource);
                     m_pTasker->addTask(this, (void *)pData);
                 }
             }
@@ -213,7 +213,7 @@ SSMRESULT CContextModel::registerContextModelEvent(IN IContextModelEvent *pConte
 
 void CContextModel::onExecute(IN void *pArg)
 {
-    int *pData = (int *)pArg;
+    intptr_t *pData = (intptr_t *)pArg;
 
     if (m_pContextModelEvent)
     {
@@ -223,7 +223,7 @@ void CContextModel::onExecute(IN void *pArg)
 
 void CContextModel::onTerminate(IN void *pArg)
 {
-    int *pData = (int *)pArg;
+    intptr_t *pData = (intptr_t *)pArg;
     SAFE_ARRAY_DELETE(pData);
 }
 
index 55238ba..1e102c2 100644 (file)
@@ -83,7 +83,7 @@ void CEvaluationEngine::onSQLTrigger(IN sqlite3_context *context, IN int argc,
 void CEvaluationEngine::onExecute(IN void *pArg)
 {
     std::map<int, IEvaluationEngineEvent *>::iterator itor;
-    int     *pData = (int *)pArg;
+    intptr_t *pData = (intptr_t *)pArg;
 
     m_mtxTriggerId.lock();
     itor = m_mapTriggers.find(pData[0]);
@@ -97,13 +97,13 @@ void CEvaluationEngine::onExecute(IN void *pArg)
 
 void CEvaluationEngine::onTerminate(IN void *pArg)
 {
-    int *pData = (int *)pArg;
+    intptr_t *pData = (intptr_t *)pArg;
     SAFE_ARRAY_DELETE(pData);
 }
 
 SSMRESULT CEvaluationEngine::onWatcherTriggered(IN int triggerId, IN int dataId)
 {
-    int     *pData = new int[2];
+    intptr_t     *pData = new intptr_t[2];
     pData[0] = triggerId;
     pData[1] = dataId;
     m_pTasker->addTask(this, (void *)pData);
@@ -912,14 +912,14 @@ SSMRESULT CEvaluationEngine::watchModelData(IN int modelId, IN ModelConditionVec
     sstream << "CREATE TRIGGER WatchInsertModel" << m_iTriggerId << " AFTER INSERT ON [ModelData" <<
             modelId << "] WHEN ";
     sstream << sstreamCondition.str().c_str() << " BEGIN SELECT OnSQLTrigger(" <<
-            (int)this << ", " << m_iTriggerId << ", NEW.dataId); END;" << std::ends;
+            reinterpret_cast<intptr_t>(this) << ", " << m_iTriggerId << ", NEW.dataId); END;" << std::ends;
     SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
     sstream.str("");
 
     sstream << "CREATE TRIGGER WatchUpdateModel" << m_iTriggerId << " AFTER UPDATE ON [ModelData" <<
             modelId << "] WHEN ";
     sstream << sstreamCondition.str().c_str() << " BEGIN SELECT OnSQLTrigger(" <<
-            (int)this << ", " << m_iTriggerId << ", NEW.dataId); END;" << std::ends;
+            reinterpret_cast<intptr_t>(this) << ", " << m_iTriggerId << ", NEW.dataId); END;" << std::ends;
     SSM_CLEANUP_ASSERT(executeSQL_NoReturn(sstream.str()));
 
     m_mtxTriggerId.lock();
index 58d2df4..91423e6 100644 (file)
@@ -364,7 +364,7 @@ void CPropagationEngine::onExecute(IN void *pArg)
 {
     SSMRESULT res = SSM_E_FAIL;
 
-    int         *pMessage = (int *)pArg;
+    intptr_t         *pMessage = (intptr_t *)pArg;
 
     RESOURCE_EVENT_TYPE eventType = (RESOURCE_EVENT_TYPE)pMessage[0];
     ISSMResource            *pResource = (ISSMResource *)pMessage[1];
@@ -395,7 +395,7 @@ CLEANUP:
 
 void CPropagationEngine::onTerminate(IN void *pArg)
 {
-    int         *pMessage = (int *)pArg;
+    intptr_t         *pMessage = (intptr_t *)pArg;
 
     delete[] pMessage;
 }
@@ -403,10 +403,10 @@ void CPropagationEngine::onTerminate(IN void *pArg)
 int CPropagationEngine::onResourceEvent(IN RESOURCE_EVENT_TYPE eventType,
                                         IN ISSMResource *pSSMResource, IN std::string info)
 {
-    int         *pMessage = new int[2];
+    intptr_t          *pMessage = new intptr_t [2];
 
     pMessage[0] = eventType;
-    pMessage[1] = (int)pSSMResource;
+    pMessage[1] = reinterpret_cast<intptr_t>(pSSMResource);
     return (int)m_pTasker->addTask(this, (void *)pMessage);
 }
 
index 62d8eca..100de71 100644 (file)
@@ -71,7 +71,7 @@ SSMRESULT CQueryEngine::processQueryResult(IN int userTriggerId,
     IContextModel           *temp_contextmodel = NULL;
     IContextModel           *temp_contextmodel2 = NULL;
 
-    int             *pData = NULL;
+    intptr_t             *pData = NULL;
 
     CDataReader *pDataReader = NULL;
 
@@ -160,10 +160,10 @@ SSMRESULT CQueryEngine::processQueryResult(IN int userTriggerId,
 
         SSM_CLEANUP_ASSERT(pDataReader->addModelData((result_model_data_id)[i].modelName, &modelDataSet));
     }
-    pData = new int[3];
+    pData = new intptr_t [3];
     pData[0] = EVENT_TYPE_OUTER;
     pData[1] = userTriggerId;
-    pData[2] = (int)pDataReader;
+    pData[2] = reinterpret_cast<intptr_t>(pDataReader);
 
     m_pTasker->addTask(this, (void *)pData);
 
@@ -234,7 +234,7 @@ CLEANUP:
 
 void CQueryEngine::onExecute(void *pArg)
 {
-    int *pData = (int *)pArg;
+    intptr_t *pData = (intptr_t *)pArg;
 
     switch (pData[0])
     {
@@ -256,7 +256,7 @@ void CQueryEngine::onExecute(void *pArg)
 
 void CQueryEngine::onTerminate(void *pArg)
 {
-    int *pData = (int *)pArg;
+    intptr_t *pData = (intptr_t *)pArg;
     std::vector<result_model>   *pResult = NULL;
     CDataReader                 *pDataReader = NULL;
 
@@ -329,10 +329,10 @@ SSMRESULT CQueryEngine::executeContextQuery(IN std::string contextQuery, OUT int
         if (validateQueryResult(pConditionedQueryResult, pResult) == SSM_S_OK)
         {
             //We have valid data, let's deliver to application.
-            int *pData = new int[3];
+            intptr_t  *pData = new intptr_t [3];
             pData[0] = EVENT_TYPE_INNER;
             pData[1] = m_cqid;
-            pData[2] = (int)pResult;
+            pData[2] = reinterpret_cast<intptr_t>(pResult);
 
             m_pTasker->addTask(this, (void *)pData);
         }
index 1217284..4c690d4 100644 (file)
@@ -21,6 +21,9 @@
 #define _SSMCore_H_
 
 #include "SSMInterface.h"
+
+using namespace OIC;
+
 #include "SSMModelDefinition.h"
 
 #define IN
index 8fe3bb2..de15320 100644 (file)
@@ -251,7 +251,7 @@ OCEntityHandlerResult SSMResourceServer::entityHandler(std::shared_ptr< OCResour
                         goto CLEANUP;
                     }
 
-                    sstream << (int) pQueryEngine;
+                    sstream << reinterpret_cast<intptr_t>(pQueryEngine);
 
                     // Register QueryEngineEvent
                     queryEngineEvent = new CQueryEngineEvent(sstream.str(), m_hSSMResource);
index 2fbcd84..668421f 100644 (file)
@@ -150,7 +150,7 @@ void CContextExecutor::registerContext(TypeofEvent callType, ISSMResource *pSSMR
 
 void CContextExecutor::onExecute(IN void *pArg)
 {
-    int         *pMessage = (int *)pArg;
+    intptr_t         *pMessage = (intptr_t *)pArg;
 
     RESOURCE_EVENT_TYPE     eventType = (RESOURCE_EVENT_TYPE)pMessage[0];
     ISSMResource            *pResource = (ISSMResource *)pMessage[1];
@@ -191,7 +191,7 @@ void CContextExecutor::onExecute(IN void *pArg)
 
 void CContextExecutor::onTerminate(IN void *pArg)
 {
-    int         *pMessage = (int *)pArg;
+    intptr_t         *pMessage = (intptr_t *)pArg;
 
     delete[] pMessage;
 }
@@ -199,10 +199,10 @@ void CContextExecutor::onTerminate(IN void *pArg)
 int CContextExecutor::onResourceEvent(RESOURCE_EVENT_TYPE eventType, ISSMResource *pSSMResource,
                                       std::string info)
 {
-    int         *pMessage = new int[2];
+    intptr_t          *pMessage = new intptr_t [2];
 
     pMessage[0] = eventType;
-    pMessage[1] = (int)pSSMResource;
+    pMessage[1] = reinterpret_cast<intptr_t>(pSSMResource);
     return (int)m_pTasker->addTask(this, (void *)pMessage);
 }
 
index c17f703..d4b133d 100644 (file)
@@ -322,55 +322,46 @@ SSMRESULT CContextRepository::loadSoftSensor(std::string softSensorName, ICtxDel
     InitContext InitializeContextFunction = NULL;
 
     // load dll(so)
-    res = SSM_E_FAIL;
-    for (unsigned int i = 1; i <= SSM_MODEL_RETRY; ++i)
-    {
-        sstream.str("");
 
 #ifdef WIN32
-        sstream << m_pathSoftSensors << softSensorName.c_str() << ".dll" << std::ends;
+    sstream << m_pathSoftSensors << softSensorName.c_str() << ".dll" << std::ends;
 
-        HINSTANCE hModule = NULL;
-        hModule = LoadLibraryA(sstream.str().c_str());
+    HINSTANCE hModule = NULL;
+    hModule = LoadLibraryA(sstream.str().c_str());
 
-        if (hModule != NULL)
-        {
-            InitializeContextFunction = (InitContext)GetProcAddress(hModule, "InitializeContext");
-        }
+    if (hModule != NULL)
+    {
+        InitializeContextFunction = (InitContext)GetProcAddress(hModule, "InitializeContext");
+    }
 #else
-        //sstream << "/data/data/com.example.javaproject/lib/lib" << modelName <<".so" << std::ends;
-        sstream << m_pathSoftSensors << "lib" << softSensorName.c_str() << ".so" << std::ends;
+    //sstream << "/data/data/com.example.javaproject/lib/lib" << modelName <<".so" << std::ends;
+    sstream << m_pathSoftSensors << "lib" << softSensorName.c_str() << ".so" << std::ends;
 
-        void *hModule = NULL;
-        hModule = dlopen(sstream.str().c_str(), RTLD_LOCAL | RTLD_LAZY);
+    void *hModule = NULL;
+    hModule = dlopen(sstream.str().c_str(), RTLD_LOCAL | RTLD_LAZY);
 
-        if (hModule != NULL)
-        {
-            InitializeContextFunction = (InitContext)dlsym(hModule, "InitializeContext");
-        }
+    if (hModule != NULL)
+    {
+        InitializeContextFunction = (InitContext)dlsym(hModule, "InitializeContext");
+    }
 #endif
-        if (hModule == NULL)
-        {
-            //load library failed. raise error
-            SSM_CLEANUP_ASSERT(SSM_E_FAIL);
-            //InitializeContextFunction = NULL;
-            //continue;
-        }
-
-        if (InitializeContextFunction != NULL)
-        {
-            InitializeContextFunction(pDelegate);
-            *hSoftSensor = hModule;
-            res = SSM_S_OK;
-        }
-        else
-        {
-            //Unload module and return error
-            SSM_CLEANUP_ASSERT(unloadSoftSensor(hModule));
-            SSM_CLEANUP_ASSERT(SSM_E_FAIL);
-        }
+    if (hModule == NULL)
+    {
+        //load library failed. raise error
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+    }
 
-        break;
+    if (InitializeContextFunction != NULL)
+    {
+        InitializeContextFunction(pDelegate);
+        *hSoftSensor = hModule;
+        res = SSM_S_OK;
+    }
+    else
+    {
+        //Unload module and return error
+        SSM_CLEANUP_ASSERT(unloadSoftSensor(hModule));
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
     }
 
 CLEANUP:
@@ -420,6 +411,8 @@ SSMRESULT CContextRepository::GetCurrentPath(std::string *path)
         SSM_CLEANUP_ASSERT(SSM_E_FAIL);
     }
 
+    buffer[length] = '\0';
+
     strPath = strrchr(buffer, '/');
 
     if (strPath == NULL)
index 1eaa069..57dbe2c 100644 (file)
@@ -1,30 +1,30 @@
 /******************************************************************
-*
-* Copyright 2014 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.
-*
-******************************************************************/
+ *
+ * Copyright 2014 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 "ResourceFinder.h"
 
 SSMRESULT CResourceFinder::finalConstruct()
 {
     SSMRESULT res = SSM_E_FAIL;
 
-    OC::PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both,
-                           "0.0.0.0", 0, OC::QualityOfService::LowQos);
+    OC::PlatformConfig cfg(OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0,
+                           OC::QualityOfService::LowQos);
 
     SSM_CLEANUP_ASSERT(CreateGlobalInstance(OID_ITasker, (IBase **)&m_pTasker));
 
@@ -46,29 +46,97 @@ SSMRESULT CResourceFinder::registerResourceFinderEvent(IN IResourceFinderEvent *
     return SSM_S_OK;
 }
 
-void CResourceFinder::onResourceFound(std::shared_ptr<OC::OCResource> resource)
+void CResourceFinder::onResourceFound(std::shared_ptr< OC::OCResource > resource)
 {
     if (resource)
     {
-        int     *pMessage = new int[2];
+        std::string path = resource->host() + resource->uri();
+
+        if (m_mapResourceHandler.find(path) != m_mapResourceHandler.end())
+            return;
+
+        intptr_t      *pMessage = new intptr_t [2];
         pMessage[0] = RESOURCE_DISCOVER_REQUESTPROFILE;
-        pMessage[1] = (int)new std::shared_ptr<OC::OCResource>(resource);
+        pMessage[1] = reinterpret_cast<intptr_t> (new  std::shared_ptr<OC::OCResource>(resource));
+
+        std::cout << "Resource Found !! >> " << path << std::endl;
 
         m_pTasker->addTask(this, pMessage);
     }
 }
 
+void CResourceFinder::presenceHandler(OCStackResult result, const unsigned int nonce,
+                                      const std::string &hostAddress)
+{
+    SSMRESULT res = SSM_E_FAIL;
+    OCStackResult ret = OC_STACK_ERROR;
+    intptr_t *pMessage = NULL;
+
+    switch (result)
+    {
+        case OC_STACK_OK:
+            ret = OC::OCPlatform::findResource("",
+                                               "coap://" + hostAddress + "/oc/core?rt=SoftSensorManager.Sensor",
+                                               std::bind(&CResourceFinder::onResourceFound, this, std::placeholders::_1));
+
+            if (ret != OC_STACK_OK)
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
+            break;
+
+        case OC_STACK_PRESENCE_STOPPED:
+        case OC_STACK_PRESENCE_TIMEOUT:
+            if (m_mapResources.find(hostAddress) != m_mapResources.end())
+            {
+                while (!m_mapResources[hostAddress].empty())
+                {
+                    pMessage = new intptr_t[2];
+                    pMessage[0] = RESOURCE_DISCOVER_UNINSTALL_RESOURCE;
+                    pMessage[1] = reinterpret_cast<intptr_t> (m_mapResourceHandler[m_mapResources[hostAddress].back()]);
+                    m_mapResources[hostAddress].pop_back();
+                    m_pTasker->addTask(this, pMessage);
+                }
+
+                m_mapResources.erase(hostAddress);
+            }
+            break;
+
+        case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
+            break;
+
+        default:
+            break;
+    }
+
+CLEANUP:
+    ;
+}
+
 SSMRESULT CResourceFinder::startResourceFinder()
 {
-    OCStackResult res = OC_STACK_ERROR;
+    SSMRESULT res = SSM_E_FAIL;
+    OCStackResult ret = OC_STACK_ERROR;
+
+    OC::OCPlatform::OCPresenceHandle presenceHandle = nullptr;
 
-    res = OC::OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=SoftSensorManager.Sensor",
+    ret = OC::OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=SoftSensorManager.Sensor",
                                        std::bind(&CResourceFinder::onResourceFound, this, std::placeholders::_1));
 
-    if (res != OC_STACK_OK)
-        return SSM_E_FAIL;
+    if (ret != OC_STACK_OK)
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
 
-    return SSM_S_OK;
+    ret = OC::OCPlatform::subscribePresence(presenceHandle, "coap://224.0.1.187",
+                                            "SoftSensorManager.Sensor",
+                                            std::bind(&CResourceFinder::presenceHandler, this, std::placeholders::_1,
+                                                    std::placeholders::_2, std::placeholders::_3));
+
+    if (ret != OC_STACK_OK)
+        SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
+    res = SSM_S_OK;
+
+CLEANUP:
+    return res;
 }
 
 SSMRESULT CResourceFinder::startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent)
@@ -84,24 +152,75 @@ SSMRESULT CResourceFinder::stopObserveResource(IN ISSMResource *pSensor)
 void CResourceFinder::onExecute(IN void *pArg)
 {
     SSMRESULT res = SSM_E_FAIL;
-    OC::QueryParamsMap  queryParams;
-    OICResourceHandler  *pResourceHandler = NULL;
-    int                 *pMessage = (int *)pArg;
-    std::shared_ptr<OC::OCResource> *pResource = NULL;
+    OCStackResult ret = OC_STACK_ERROR;
+    OC::QueryParamsMap queryParams;
+    OICResourceHandler *pResourceHandler = NULL;
+    intptr_t                 *pMessage =  reinterpret_cast<intptr_t *>(pArg);
+    std::shared_ptr< OC::OCResource > *pResource = NULL;
+    OC::OCPlatform::OCPresenceHandle presenceHandle = NULL;
+
+    std::string resourceHostAddress = "";
+    std::string resourceFullPath = "";
 
     switch (pMessage[0])
     {
         case RESOURCE_DISCOVER_REQUESTPROFILE:
-            pResource = (std::shared_ptr<OC::OCResource> *)pMessage[1];
+            pResource = (std::shared_ptr< OC::OCResource > *) pMessage[1];
             pResourceHandler = new OICResourceHandler();
             SSM_CLEANUP_ASSERT(pResourceHandler->initHandler(*pResource, this));
-            m_mapResourceHandler[pResource->get()->host() + pResource->get()->uri()] = pResourceHandler;
-            pResource->get()->get(queryParams, std::bind(&OICResourceHandler::onGetResourceProfile,
-                                  pResourceHandler, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+
+            resourceFullPath = pResource->get()->host() + pResource->get()->uri();
+
+            resourceHostAddress = pResource->get()->host();
+            resourceHostAddress.erase(0, 7);        // erase 'coap://'
+
+            m_mapResourceHandler[resourceFullPath] = pResourceHandler;
+
+            m_mapResources[resourceHostAddress].push_back(resourceFullPath);
+
+            ret = pResource->get()->get(queryParams,
+                                        std::bind(&OICResourceHandler::onGetResourceProfile, pResourceHandler,
+                                                  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
+
+            if (ret != OC_STACK_OK)
+                SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
+            break;
+
+        case RESOURCE_DISCOVER_INSTALL_RESOURCE:
+            if (m_mapResourcePresenceHandles.find(((ISSMResource *)pMessage[1])->ip) ==
+                m_mapResourcePresenceHandles.end())
+            {
+                ret = OC::OCPlatform::subscribePresence(presenceHandle, ((ISSMResource *)pMessage[1])->ip,
+                                                        "SoftSensorManager.Sensor",
+                                                        std::bind(&CResourceFinder::presenceHandler, this, std::placeholders::_1,
+                                                                std::placeholders::_2, std::placeholders::_3));
+
+                if (ret != OC_STACK_OK)
+                    SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
+                m_mapResourcePresenceHandles[((ISSMResource *)pMessage[1])->ip] = presenceHandle;
+            }
+
+            m_pResourceFinderEvent->onResourceFound((ISSMResource *) pMessage[1]);
             break;
 
-        case RESOURCE_DISCOVER_SETUP_RESOURCE:
-            m_pResourceFinderEvent->onResourceFound((ISSMResource *)pMessage[1]);
+        case RESOURCE_DISCOVER_UNINSTALL_RESOURCE:
+            m_pResourceFinderEvent->onResourceLost(&((OICResourceHandler *) pMessage[1])->m_SSMResource);
+
+            if (m_mapResourcePresenceHandles.find(((OICResourceHandler *)pMessage[1])->m_SSMResource.ip) !=
+                m_mapResourcePresenceHandles.end())
+            {
+                ret = OC::OCPlatform::unsubscribePresence(
+                          m_mapResourcePresenceHandles[((OICResourceHandler *)pMessage[1])->m_SSMResource.ip]);
+
+                if (ret != OC_STACK_OK)
+                    SSM_CLEANUP_ASSERT(SSM_E_FAIL);
+
+                m_mapResourcePresenceHandles.erase(((OICResourceHandler *)pMessage[1])->m_SSMResource.ip);
+            }
+
+            m_mapResourceHandler.erase(((OICResourceHandler *) pMessage[1])->m_SSMResource.name);
             break;
     }
 
@@ -111,17 +230,20 @@ CLEANUP:
 
 void CResourceFinder::onTerminate(IN void *pArg)
 {
-    std::shared_ptr<OC::OCResource>     *pResource = NULL;
-    int                 *pMessage = (int *)pArg;
+    std::shared_ptr< OC::OCResource > *pResource = NULL;
+    intptr_t *pMessage = (intptr_t *)pArg;
 
     switch (pMessage[0])
     {
         case RESOURCE_DISCOVER_REQUESTPROFILE:
-            pResource = (std::shared_ptr<OC::OCResource> *)pMessage[1];
+            pResource = (std::shared_ptr< OC::OCResource > *) pMessage[1];
             delete pResource;
             break;
 
-        case RESOURCE_DISCOVER_SETUP_RESOURCE:
+        case RESOURCE_DISCOVER_INSTALL_RESOURCE:
+            break;
+
+        case RESOURCE_DISCOVER_UNINSTALL_RESOURCE:
             break;
     }
 
index b070a77..1ad2ccf 100644 (file)
@@ -1,22 +1,22 @@
 /******************************************************************
-*
-* Copyright 2014 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.
-*
-******************************************************************/
+ *
+ * Copyright 2014 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 _ResourceFinder_H_
 #define _ResourceFinder_H_
 
 #include "OCPlatform.h"
 #include "OCApi.h"
 
-class CResourceFinder :
-    public CObjectRoot<CObjectMultiThreadModel>
-    , public IResourceFinder
-    , public IThreadClient
+class CResourceFinder: public CObjectRoot< CObjectMultiThreadModel >,
+    public IResourceFinder,
+    public IThreadClient
 {
     public:
         SSMRESULT queryInterface(const OID &objectID, IBase **ppObject)
@@ -39,7 +38,7 @@ class CResourceFinder :
 
             if (IsEqualOID(objectID, OID_IResourceFinder))
             {
-                IBase *pBase = (IResourceFinder *)this;
+                IBase *pBase = (IResourceFinder *) this;
                 pBase->addRef();
                 *ppObject = pBase;
                 return SSM_S_OK;
@@ -52,7 +51,9 @@ class CResourceFinder :
         void finalRelease();
 
         SSMRESULT registerResourceFinderEvent(IN IResourceFinderEvent *pEvent);
-        void onResourceFound(std::shared_ptr<OC::OCResource> resource);
+        void onResourceFound(std::shared_ptr< OC::OCResource > resource);
+        void presenceHandler(OCStackResult result, const unsigned int nonce,
+                             const std::string &hostAddress);
         SSMRESULT startResourceFinder();
 
         SSMRESULT startObserveResource(IN ISSMResource *pSensor, IN IEvent *pEvent);
@@ -65,22 +66,24 @@ class CResourceFinder :
         class OICResourceHandler
         {
             public:
+                ISSMResource m_SSMResource;
+
                 OICResourceHandler()
                 {
                     m_pEvent = NULL;
                     m_pResourceFinderClient = NULL;
                 }
 
-                SSMRESULT initHandler(std::shared_ptr<OC::OCResource> resource, IN IThreadClient    *pThreadClient)
+                SSMRESULT initHandler(std::shared_ptr< OC::OCResource > resource,
+                                      IN IThreadClient *pThreadClient)
                 {
-                    SSMRESULT   res = SSM_E_FAIL;
+                    SSMRESULT res = SSM_E_FAIL;
 
                     SSM_CLEANUP_ASSERT(CreateGlobalInstance(OID_ITasker, (IBase **)&m_pTasker));
                     m_pResource = resource;
                     m_pResourceFinderClient = pThreadClient;
 
-CLEANUP:
-                    return res;
+CLEANUP: return res;
                 }
 
                 SSMRESULT startObserve(IEvent *pEvent)
@@ -90,8 +93,9 @@ CLEANUP:
                     m_pEvent = pEvent;
 
                     m_pResource.get()->observe(OC::ObserveType::Observe, queryParams,
-                                               std::bind(&OICResourceHandler::onResourceDataReceived,
-                                                         this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
+                                               std::bind(&OICResourceHandler::onResourceDataReceived, this,
+                                                         std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+                                                         std::placeholders::_4));
 
                     return SSM_S_OK;
                 }
@@ -104,14 +108,14 @@ CLEANUP:
                 }
 
                 void onResourceDataReceived(const OC::HeaderOptions headerOptions,
-                                            const OC::OCRepresentation &representation,
-                                            const int &eCode, const int &sequenceNumber)
+                                            const OC::OCRepresentation &representation, const int &eCode,
+                                            const int &sequenceNumber)
                 {
                     if (eCode == 0)
                     {
-                        std::vector<ContextData>        lstCtxData;
-                        ContextData             ctxData;
-                        std::map<std::string, std::string>  outputProperty;
+                        std::vector< ContextData > lstCtxData;
+                        ContextData ctxData;
+                        std::map< std::string, std::string > outputProperty;
 
                         //Bind data
                         ctxData.rootName = m_pResource->uri().substr(1);
@@ -135,7 +139,7 @@ CLEANUP:
                         }
                         else
                         {
-                            ;//Payload is empty!!
+                            ; //Payload is empty!!
                         }
                     }
                 }
@@ -146,18 +150,17 @@ CLEANUP:
                     //unpack attributeMap
 
                     //Create SSMResource using OCResource attributeMap
-                    std::map<std::string, std::string>      outputProperty;
-                    ISSMResource        *pSSMResource = new ISSMResource();
-                    pSSMResource->location = SENSOR_LOCATION_REMOTE;
-                    pSSMResource->name = m_pResource->host() + m_pResource->uri();
-                    pSSMResource->type = m_pResource->uri().substr(1);
-                    pSSMResource->ip = m_pResource->host();
+                    std::map< std::string, std::string > outputProperty;
+                    m_SSMResource.location = SENSOR_LOCATION_REMOTE;
+                    m_SSMResource.name = m_pResource->host() + m_pResource->uri();
+                    m_SSMResource.type = m_pResource->uri().substr(1);
+                    m_SSMResource.ip = m_pResource->host();
 
                     //bind default properties
                     outputProperty["name"] = "lifetime";
                     outputProperty["type"] = "int";
                     outputProperty["value"] = "0";
-                    pSSMResource->outputProperty.push_back(outputProperty);
+                    m_SSMResource.outputProperty.push_back(outputProperty);
 
                     //bind default primitive sensor property, value to resource class for schema creating
 
@@ -167,22 +170,22 @@ CLEANUP:
                         outputProperty["name"] = representation.getValue<std::string>(toString(i * 3));
                         outputProperty["type"] = representation.getValue<std::string>(toString(i * 3 + 1));
                         outputProperty["value"] = representation.getValue<std::string>(toString(i * 3 + 2));
-                        pSSMResource->outputProperty.push_back(outputProperty);
+                        m_SSMResource.outputProperty.push_back(outputProperty);
                     }
                     /////////////////////////////////////////////////////
                     //
-                    int     *pMessage = new int[2];
-                    pMessage[0] = RESOURCE_DISCOVER_SETUP_RESOURCE;
-                    pMessage[1] = (int)pSSMResource;
+                    intptr_t      *pMessage = new intptr_t [2];
+                    pMessage[0] = RESOURCE_DISCOVER_INSTALL_RESOURCE;
+                    pMessage[1] = reinterpret_cast<intptr_t>(&m_SSMResource);
 
-                    m_pTasker->addTask(m_pResourceFinderClient, (void *)pMessage);
+                    m_pTasker->addTask(m_pResourceFinderClient, (void *) pMessage);
                 }
 
             private:
-                CObjectPtr<ITasker>                 m_pTasker;
-                std::shared_ptr<OC::OCResource>     m_pResource;
-                IThreadClient                       *m_pResourceFinderClient;
-                IEvent                              *m_pEvent;
+                CObjectPtr< ITasker > m_pTasker;
+                std::shared_ptr< OC::OCResource > m_pResource;
+                IThreadClient *m_pResourceFinderClient;
+                IEvent *m_pEvent;
 
                 std::string toString(int t)
                 {
@@ -192,10 +195,19 @@ CLEANUP:
                 }
         };
 
-        enum RESOURCE_DISCOVER_STATE {RESOURCE_DISCOVER_REQUESTPROFILE, RESOURCE_DISCOVER_SETUP_RESOURCE};
-        IResourceFinderEvent                *m_pResourceFinderEvent;
-        CObjectPtr<ITasker>             m_pTasker;
-        std::map<std::string , OICResourceHandler *> m_mapResourceHandler;
+        enum RESOURCE_DISCOVER_STATE
+        {
+            RESOURCE_DISCOVER_REQUESTPROFILE,
+            RESOURCE_DISCOVER_INSTALL_RESOURCE,
+            RESOURCE_DISCOVER_UNINSTALL_RESOURCE
+        };
+        IResourceFinderEvent *m_pResourceFinderEvent;
+        CObjectPtr< ITasker > m_pTasker;
+        std::map< std::string, OICResourceHandler * > m_mapResourceHandler;
+        std::map< std::string, std::vector<std::string> >
+        m_mapResources;    // <hostaddress, std::vector<resources> >
+        std::map< std::string, OC::OCPlatform::OCPresenceHandle >
+        m_mapResourcePresenceHandles;     // <hostaddress, presence handler>
 };
 
 #endif
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile
new file mode 100644 (file)
index 0000000..6df468b
--- /dev/null
@@ -0,0 +1,130 @@
+# //******************************************************************
+# //
+# // Copyright 2014 Intel Mobile Communications GmbH 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 ../../../../build/arduino/environment.mk
+ARDUINO_DIR = /usr/share/arduino
+
+BUILD := release
+PLATFORM := arduinomega
+ARDUINO_PORT := ttyACM0
+
+SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
+OBJPATH=${SRCLIST:.cpp=.o}
+OBJLIST=${notdir ${OBJPATH}}
+
+SRC_PATH=../src
+# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
+ARDUINOWIFI := 0
+
+APP_NAME := reference
+
+TB_DIR = ../../../../../../resource/csdk
+LOGGER_DIR = $(TB_DIR)/logger
+OC_LOG_DIR = $(TB_DIR)/../oc_logger
+TBSTACK_DIR = $(TB_DIR)/stack
+TBSOCKET_DIR = $(TB_DIR)/ocsocket
+
+include $(TB_DIR)/local.properties
+include $(TB_DIR)/$(PLATFORM).properties
+
+VPATH := $(SDIR_ARD_PLATFORM)
+
+#include directories
+OCSOCK_DIR = $(TB_DIR)/ocsocket
+LOGGER_DIR = $(TB_DIR)/logger
+STACK_DIR  = $(TB_DIR)/stack
+INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include -I../include
+
+CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
+CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
+
+CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
+
+ifeq ($(ARDUINOWIFI),1)
+       CFLAGS += -DARDUINOWIFI
+       ARDUINO_SHIELD_TYPE := "/wifi_shield"
+       TRANSPORT_OBJS = $(WIFI_COBJ)
+else
+       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
+       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
+endif
+
+OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
+
+OBJ_DIR := $(OUT_DIR)/bin
+
+all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
+
+core.a: $(PLATFORM_OBJS)
+       @cd $(OBJ_DIR) && $(AR) -x ../../../../$(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a
+       $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o
+       @cd $(OBJ_DIR) && $(RANLIB) $@
+
+prep_dirs:
+       -mkdir $(PLATFORM)
+       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
+       -mkdir $(OUT_DIR)
+       -mkdir $(OBJ_DIR)
+
+%.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+%.o: %.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
+%.o: ${SRC_PATH}/%.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+$(APP_NAME).elf: $(OBJLIST) core.a
+ifeq ($(PLATFORM),arduinomega)
+       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@
+else ifeq ($(PLATFORM),arduinodue)
+       $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+$(APP_NAME).hex: $(APP_NAME).elf
+ifeq ($(PLATFORM),arduinomega)
+       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep
+       $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@
+else ifeq ($(PLATFORM),arduinodue)
+       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+install: all
+ifeq ($(PLATFORM),arduinomega)
+       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i
+else ifeq ($(PLATFORM),arduinodue)
+       stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb
+       $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+.PHONY: clean
+
+clean: legacy_clean
+       rm -rf arduinomega
+       rm -rf arduinodue
+
+legacy_clean:
+       @rm -rf bin
+       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h
new file mode 100644 (file)
index 0000000..8356098
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * bleLib.h
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#ifndef BLELIB_H_
+#define BLELIB_H_
+
+#include "Arduino.h"
+
+#define BLE_NOCHANGE   -1
+#define BLE_MASTER             1
+#define BLE_SLAVER             0
+
+#define BLE_DISCON             200
+#define BLE_NODATA             100
+
+
+/***************************************
+ *
+ *     HM-10 BLE Module Control Class.
+ *     Target Board : Arduino-Mega.
+ *
+ **************************************/
+class Cble
+{
+public :
+       /***
+        * BLE Control Function.
+        */
+       // BLE initialization ( COM baud rate , BLE Master , Slave setting. )
+       void init(long baudRate, int ble_mode, char* SelfMaxAddr);
+
+       void StatusRead( void );
+
+       bool IsSelfArduino( void );
+
+       bool IsConnected( void );
+
+       bool pollingConnect( const char* maxAddr );
+
+       void pollingDisconnect( void );
+       // Get RSSI by BLE communication. (polling method.)
+       int pollingGetRSSI( void );
+       // Send Request to BLE Module. And, Get the response. (polling method.)
+       bool pollingRequest(const char* request, char* data, int dataLen);
+
+       int mustHaveRequest(const char* request, char* data, int dataLen);
+
+       void streamDummy( char* data, int dataLen);
+
+       /***
+        * Debug COM port to BLE COM port.
+        * BLE COM port to Debug COM port.
+        */
+       // BLE Module to Debug Serial port.
+       void BLE2Debug( int autoDiscon );
+       // Debug Serial port to BLE Module.
+       char* Debug2BLE( int BLEwrite );
+
+       /***
+        * If you first setting, you need next-function.
+        */
+       // Restore to factory setting data.
+       void FactoryReset( void );
+       // First setting of COM port.
+       void firstUartSetting( void );
+};
+
+
+
+#if 0
+#define debug_printf(...)      {                                                       \
+       char* __temp__ = (char*)malloc(sizeof(char)*2048);              \
+       sprintf(__temp__, __VA_ARGS__ );                                        \
+       Serial.print(__temp__);                                                                 \
+       free(__temp__);                                                                                                 \
+}
+#else
+#define debug_printf(...)
+#endif
+
+
+
+#endif /* BLELIB_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h
new file mode 100644 (file)
index 0000000..41556f6
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * oic_lanLib.h
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#ifndef OIC_LANLIB_H_
+#define OIC_LANLIB_H_
+
+
+int ConnectToNetwork();
+
+
+#endif /* OIC_WIFILIB_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp
new file mode 100644 (file)
index 0000000..c4e12d3
--- /dev/null
@@ -0,0 +1,584 @@
+/*
+ * blsLib.cpp
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#include "bleLib.h"
+#include <stdarg.h>
+
+#define ARDUINO                        1
+//#define __INTERNAL_DEBUG__           1
+
+
+#define LIMIT_COUNT                    100
+#define DUMMY_SIZE                     30
+#define DEBUG_SIZE                     DUMMY_SIZE
+#if (ARDUINO != 0)
+#define SERIAL_SIZE                    100
+#endif
+
+#define BLE            Serial2
+
+bool isConnected = false;
+int SerialCnt=0;
+int BLECnt=0;
+char SelfMaxaddr[19] = {0,};
+
+char debugD[DEBUG_SIZE]={0,};
+
+#if (ARDUINO != 0)
+char SerialData[SERIAL_SIZE]={0,};
+char BLEData[SERIAL_SIZE]={0,};
+#endif
+
+// baudRate이 115200이면, 주의해야한다.
+// Arduino Chip은 16bit Process 이므로 int형의 사이즈가 4byte형 signed int이다.
+void Cble::init(long baudRate, int ble_mode, char* SelfMaxAddr)
+{
+       debug_printf("BLE shiled is initialed.-\r\n");
+
+       if(SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE )
+       {
+               debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n");
+               exit(-1);
+       }
+       sprintf(SelfMaxaddr, "%s",SelfMaxAddr);
+
+       BLE.begin(baudRate);
+       BLE.setTimeout(1);
+       delay(1000);
+
+       memset(debugD,0,DEBUG_SIZE);
+
+       if( ble_mode != BLE_NOCHANGE )
+       {
+               while( IsSelfArduino() == false )
+                       this->pollingDisconnect();
+       }
+
+       if( ble_mode == BLE_MASTER )
+       {
+               pollingRequest("AT+ROLE1", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+MODE0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+NOTI0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+       }
+       else if ( ble_mode == BLE_SLAVER )
+       {
+               pollingRequest("AT+ROLE0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+MODE2", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+NOTI0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+       }
+
+       if( ble_mode != BLE_NOCHANGE )
+       {
+               while( IsSelfArduino() == false )
+                       this->pollingDisconnect();
+       }
+
+       delay(250);
+}
+
+void Cble::StatusRead( void )
+{
+       debug_printf("StatusRead function called.\r\n");
+
+       pollingRequest("AT+ROLE?", debugD, 9);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+MODE?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+IMME?", debugD, 9);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+TYPE?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+POWE?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+NOTI?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+PIO1?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+}
+
+bool Cble::IsConnected( void )
+{
+       return isConnected;
+}
+
+bool Cble::IsSelfArduino( void )
+{
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("IsSelfArduino is called.\r\n");
+#endif
+       int length=mustHaveRequest("AT+ADDR?", debugD, 20);
+
+       if( strstr(debugD, SelfMaxaddr) )
+       {
+               isConnected = false;
+               memset(debugD,0,length);
+               return true;
+       }
+       else
+       {
+               isConnected = true;
+               memset(debugD,0,length);
+               return false;
+       }
+}
+
+bool Cble::pollingConnect( const char* maxAddr )
+{
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("pollingConnect is called.\r\n");
+#endif
+
+#define CONNECT_SIZE           20
+
+       char cmd[CONNECT_SIZE]= {0,};
+
+       // is Connected Address ?
+       pollingRequest("AT+ADDR?", debugD, 20);
+       if( strstr(debugD, maxAddr) )
+       {
+               isConnected = true;
+               memset(debugD,0,DEBUG_SIZE);
+               return isConnected;
+       }
+       memset(debugD,0,DEBUG_SIZE);
+
+       // Try Connection.
+       sprintf(cmd, "AT+CON%s",maxAddr);
+       if( pollingRequest(cmd, debugD, 8) == false )
+       {
+               debug_printf("Error : %s command is failed.\r\n",cmd );
+               memset(debugD,0,DEBUG_SIZE);
+               pollingDisconnect();
+               return false;
+       }
+       else if( strstr(debugD,"OK+CONNA") )
+       {
+               isConnected = true;
+               memset(debugD,0,DEBUG_SIZE);
+       }
+       else
+       {
+               memset(debugD,0,DEBUG_SIZE);
+               pollingDisconnect();
+               return false;
+       }
+
+       // Confirm Connected Address.
+       pollingRequest("AT+ADDR?", debugD, 20);
+
+       if( strstr(debugD, maxAddr) == 0 )
+       {
+               isConnected = false;
+               if ( strstr(debugD, "OK+CONNF") )
+               {
+                       memset(debugD,0,DEBUG_SIZE);
+                       streamDummy(debugD, 8);
+               }
+       }
+       memset(debugD,0,DEBUG_SIZE);
+       delay(5);
+
+       return isConnected;
+
+#undef CONNECT_SIZE
+}
+
+
+#define  CMD_DISCONNECT                "(CMD_DISCON)"
+void Cble::pollingDisconnect( void )
+{
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("pollingDisconnect is called.\r\n");
+#endif
+       int length=0;
+#if (ARDUINO == 0)
+       pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL);
+       delay(5);
+
+       length=mustHaveRequest("AT", debugD, 2);
+       if( strstr(debugD,"OK") )
+               isConnected = false;
+
+       memset(debugD,0,length);
+#else
+       if( BLE.available() )
+       {
+               if( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true )
+               {
+                       debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT);
+
+                       do {
+                               debug_printf("pollingDisconnect : Send AT message.\r\n");
+                               if( length )
+                                       memset(debugD, 0, length);
+
+                               length=mustHaveRequest("AT", debugD, 2);
+                       }while( strstr(debugD,"OK") == NULL );
+
+                       debug_printf("pollingDisconnect() is Success.\r\n");
+                       memset(debugD, 0, length);
+               }
+       }
+#endif
+
+       delay(5);
+}
+
+int Cble::pollingGetRSSI( void )
+{
+#define RSSI_SIZE              11
+#define RSSI_POS               7
+
+       long time_cnt=0;
+       char c=0;
+       char index=0;
+       char rssi_res[RSSI_SIZE] = {0,};
+
+       streamDummy(NULL, NULL);
+
+       if( isConnected == true )
+       {
+               BLE.write("AT+RSSI?");
+               BLE.flush();
+               delay(5);
+
+               while(1)
+               {
+                       if ( BLE.available() )
+                               c = (char)BLE.read();
+                       else
+                       {
+                               c = 0;
+                               time_cnt++;
+                       }
+
+                       if( c )
+                       {
+                               rssi_res[index] = c;
+                               index++;
+                               if( index == RSSI_SIZE-1 )
+                               {
+                                       rssi_res[index] = '\0';
+                                       goto RESULT;
+                               }
+                       }
+
+                       if( time_cnt == 0xFFFFF )
+                       {
+                               debug_printf("Error : Time Out GetRSSI().\r\n");
+                               return BLE_NODATA;
+                       }
+
+               }
+
+       RESULT :
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("res= %s \r\n",rssi_res);
+#endif
+               char* Srssi = &(rssi_res[RSSI_POS]);
+               int rssi = atoi(Srssi);
+
+               return rssi;
+       }
+
+       return BLE_DISCON;
+
+#undef RSSI_POS
+#undef RSSI_SIZE
+}
+
+int Cble::mustHaveRequest(const char* request, char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       BLE.write(request);
+       BLE.flush();
+       delay(150);
+
+READ_STREAM :
+       while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+       {
+               cnt++;
+               delay(10);
+
+               if ( cnt >= LIMIT_COUNT/10 )
+               {
+#ifdef __INTERNAL_DEBUG__
+                       debug_printf("=====> Retry Request command Send. <=========\r\n");
+#endif
+                       cnt = 0;
+                       BLE.write(request);
+                       BLE.flush();
+
+                       required_length = dataLen;
+                       data_index = data;
+                       length = 0;
+                       delay(50);
+               }
+       }
+
+       required_length -= length;
+       if( required_length != 0 )
+       {
+               data_index = data_index + length;
+               length = 0;
+               goto READ_STREAM;
+       }
+
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       return dataLen;
+}
+
+bool Cble::pollingRequest(const char* request, char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       BLE.write(request);
+       BLE.flush();
+
+       if( data_index )
+       {
+               delay(250);
+
+READ_STREAM :
+               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+               {
+                       cnt++;
+                       if ( cnt >= LIMIT_COUNT )
+                       {
+                               debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request);
+                               return false;
+                       }
+               }
+
+               required_length -= length;
+               if( required_length != 0 )
+               {
+                       data_index = data_index + length;
+                       length = 0;
+                       goto READ_STREAM;
+               }
+
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       }
+       return true;
+}
+
+void Cble::streamDummy( char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       if( data && required_length )
+       {
+READ_STREAM :
+               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+               {
+                       cnt++;
+                       if ( cnt >= LIMIT_COUNT )
+                       {
+                               debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n");
+                               return ;
+                       }
+               }
+
+               required_length -= length;
+               if( required_length != 0 )
+               {
+                       data_index = data_index + length;
+                       length = 0;
+                       goto READ_STREAM;
+               }
+
+               debug_printf("[ streamDummy ] %s\r\n\r\n", data);
+       }
+       else
+       {
+               if( BLE.available() )
+               {
+                       BLE.readBytes(debugD, DEBUG_SIZE);
+#ifdef __INTERNAL_DEBUG__
+                       debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
+#endif
+                       memset(debugD, 0, DEBUG_SIZE);
+               }
+       }
+
+}
+
+#if (ARDUINO != 0)
+
+#define REGARD_DISCON                  5000
+int needDiscon = 0;
+unsigned long global_cnt = 0;
+
+void Cble::BLE2Debug( int autoDiscon )
+{
+       int cnt=0;
+       uint8_t length=0;
+
+       if( BLE.available() )
+       {
+               while( (length=BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 )
+               {
+                       cnt++;
+                       if ( cnt >= LIMIT_COUNT )
+                               return ;
+               }
+
+               global_cnt = 0;
+               needDiscon = 0;
+
+               Serial.println(BLEData);
+               memset(BLEData, 0, length);
+       }
+       else if ( autoDiscon )
+       {
+               global_cnt++;
+//             debug_printf("global_cnt=%u , ", global_cnt );
+//             debug_printf("needDiscon=%d\r\n", needDiscon);
+               if( !needDiscon && global_cnt >= REGARD_DISCON )
+               {
+                       needDiscon = 1;
+                       debug_printf("result : global_cnt=%u , ", global_cnt );
+                       debug_printf("needDiscon=%d\r\n", needDiscon);
+               }
+
+               if ( needDiscon )
+               {
+                       debug_printf("Auto Discon : global_cnt=%u , ", global_cnt );
+                       debug_printf("needDiscon=%d\r\n", needDiscon);
+                       if( pollingRequest("AT", debugD, 2) == true )
+                       {
+                               global_cnt = 0;
+                               needDiscon = 0;
+                       }
+               }
+       }
+}
+
+char* Cble::Debug2BLE( int BLEwrite )
+{
+       char* result = NULL;
+
+       if( Serial.available() )
+       {
+               char c = (char)Serial.read();
+
+               switch(c)
+               {
+               case '\0':
+                       return result;
+               case '\r':
+               case '\n':
+                       debug_printf("\r\n");
+                       if(BLEwrite && SerialCnt)
+                       {
+                               BLE.write(SerialData);
+                               BLE.flush();
+                       }
+
+                       result = (char*)malloc(sizeof(char)*(SerialCnt+1));
+                       memcpy(result, SerialData, SerialCnt );
+                       result[SerialCnt] = NULL;
+
+                       memset(SerialData, 0, SerialCnt+1);
+                       SerialCnt=0;
+                       break;
+               default :
+                       SerialData[SerialCnt] = c;
+                       SerialCnt++;
+                       Serial.print(c);
+                       break;
+               }
+       }
+
+       return result;
+}
+#else
+void Cble::BLE2Debug( int autoDiscon )
+{
+       ;
+}
+
+char* Cble::Debug2BLE( int BLEwrite )
+{
+        return NULL;
+}
+#endif
+
+void Cble::FactoryReset( void )
+{
+       debug_printf("FactoryReset is called.\r\n");
+
+       pollingRequest("AT+RENEW", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+}
+
+
+void Cble::firstUartSetting( void )
+{
+       debug_printf("firstUartSetting is called.\r\n");
+
+       Serial.begin(9600);
+       BLE.begin(9600);
+       BLE.setTimeout(1);
+       delay(1000);
+
+       pollingRequest("AT+BAUD4", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+
+       debug_printf("Please Power off and on.\r\n");
+       BLE.end();
+//     delay(1000);
+//
+//     BLE.begin(115200);
+//     delay(1000);
+//
+//     pollingRequest("AT", debugD, DEBUG_SIZE);
+//     memset(debugD, 0, DEBUG_SIZE);
+
+
+       exit(0);
+}
+
+
+
+
+
+
+
+
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp
new file mode 100644 (file)
index 0000000..c4a4f26
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * oic_wifiLib.cpp
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+// proximity code e
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+
+PROGMEM const char TAG[] = "ReferenceSensor";
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+
+/// WiFi Shield firmware with Intel patches
+static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
+
+/// WiFi network info and credentials
+char ssid[] = "SoftSensor_AP";
+char pass[] = "1234567890";
+//char ssid[] = "SoftSensor_2.4G";
+//char pass[] = "12344321";
+
+int ConnectToNetwork()
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
+        return -1;
+    }
+
+    // Verify that WiFi Shield is running the firmware with all UDP fixes
+    fwVersion = WiFi.firmwareVersion();
+    OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
+    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
+    {
+        OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        return -1;
+    }
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED)
+    {
+        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+        status = WiFi.begin(ssid,pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+    }
+    OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
+
+    IPAddress ip = WiFi.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#else
+// Arduino Ethernet Shield
+int ConnectToNetwork()
+{
+    // Note: ****Update the MAC address here with your shield's MAC address****
+    uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAC};
+
+    uint8_t error = Ethernet.begin(ETHERNET_MAC);
+    if (error  == 0)
+    {
+        OC_LOG_V(ERROR, TAG, "error is: %d", error);
+        return -1;
+    }
+    IPAddress ip = Ethernet.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#endif //ARDUINOWIFI
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/readme.txt b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/readme.txt
new file mode 100644 (file)
index 0000000..7c041e1
--- /dev/null
@@ -0,0 +1,19 @@
+
+Followings should be done befor building Arudno applications 
+
+1. Applications on arduino conform  the Iotivity Base released on 22-Aug-2014.
+   (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
+
+   For successful execution, you have to copy the file, local.properties, into the following pathes:
+    - oic-resource/csdk/
+    - oic-resource/csdk/libcoap-4.1.1
+
+
+2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
+
+   Makefile path:  / oic-resource / csdk / libcoap-4.1.1 / makefile
+
+   path to be modified: 
+  
+     - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
+     - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp
new file mode 100644 (file)
index 0000000..953032e
--- /dev/null
@@ -0,0 +1,308 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+#include "bleLib.h"
+#include <stdio.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "oic_lanLib.h"
+
+#define ARDUINO_AVR_MEGA2560 1
+/// This is the port which Arduino Server will use for all unicast communication with it's peers
+#define OC_WELL_KNOWN_PORT 5683
+
+#define JSON_BASE00 "{\"href\":\"\",\"rep\":{"
+#define JSON_BASE01 "\"0\":\"MAC\",\"1\":\"string\",\"2\":\""
+#define JSON_BASE02 "\",\"3\":\"SERVICETYPE\",\"4\":\"string\",\"5\":\""
+#define JSON_BASE03 "\"}}"
+
+typedef struct REFERRESOURCE {
+    OCResourceHandle m_handle;
+    char* m_macaddress;
+    char* m_servicetype;
+} REFERResource;
+
+PROGMEM const char TAG[] = "ReferenceSensor";
+
+REFERResource REFER;
+Cble ble;
+
+char macaddress[13]={"9059AF1704D7"};
+char servicetype[15]={"BOOK"};
+
+int g_REFERUnderObservation = 0;
+
+const char *getResult(OCStackResult result);
+void createREFERResource();
+
+#define LENGTH_VAR             100
+static int base_length = 0;
+
+bool JsonGenerator( REFERResource& ref, char* jsonBuf, uint16_t buf_length )
+{
+       if( (buf_length - base_length) < LENGTH_VAR )
+       {
+               OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+               return false;
+       }
+
+       sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%s",ref.m_macaddress);
+       sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03, ref.m_servicetype);
+
+       Serial.println(jsonBuf);
+
+       return true;
+}
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+    //This var is declared in avr-libc/stdlib/malloc.c
+    //It keeps the largest address not allocated for heap
+    extern char *__brkval;
+    //address of tmp gives us the current stack boundry
+    int tmp;
+    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+             ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+
+// This is the entity handler for the registered resource.
+// This is invoked by OCStack whenever it recevies a request for this resource.
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
+{
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCEntityHandlerResponse response = {0};
+    char payload[MAX_RESPONSE_LENGTH] = {0};
+
+    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+        if(OC_REST_GET == entityHandlerRequest->method)
+        {
+                if(JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH))
+                {
+                }
+           else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        if(OC_REST_PUT == entityHandlerRequest->method)
+        {
+            //Do something with the 'put' payload
+            if (JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+         }
+    }
+
+    if (ehRet == OC_EH_OK)
+   {
+          // Format the response.  Note this requires some info about the request
+          response.requestHandle = entityHandlerRequest->requestHandle;
+          response.resourceHandle = entityHandlerRequest->resource;
+          response.ehResult = ehRet;
+          response.payload = (unsigned char *)payload;
+          response.payloadSize = strlen(payload);
+          response.numSendVendorSpecificHeaderOptions = 0;
+          memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+          memset(response.resourceUri, 0, sizeof response.resourceUri);
+          // Indicate that response is NOT in a persistent buffer
+          response.persistentBufferFlag = 0;
+
+          // Send the response
+          if (OCDoResponse(&response) != OC_STACK_OK)
+          {
+                  OC_LOG(ERROR, TAG, "Error sending response");
+                  ehRet = OC_EH_ERROR;
+          }
+    }
+
+    if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
+    {
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
+            g_REFERUnderObservation = 1;
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
+        }
+    }
+
+    return ehRet;
+}
+
+
+char tempdata[200];
+void ChangeREFERRepresentation (void *param)
+{
+       (void)param;
+       OCStackResult result = OC_STACK_ERROR;
+       result = OCNotifyAllObservers (REFER.m_handle, OC_NA_QOS);
+
+       OC_LOG_V(INFO, TAG, "%s", JsonGenerator( REFER, tempdata, 200));
+
+       if (OC_STACK_NO_OBSERVERS == result)
+       {
+               OC_LOG_V(INFO, TAG, "g_REFERUnderObservation is 0." );
+               g_REFERUnderObservation = 0;
+       }
+}
+
+//The setup function is called once at startup of the sketch
+void setup()
+{
+       Serial.begin(115200);
+
+   REFER.m_macaddress = macaddress;
+   REFER.m_servicetype = servicetype;
+
+       // Add your initialization code here
+       OC_LOG_INIT();
+
+       OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+
+       // Connect to Ethernet or WiFi network
+       if (ConnectToNetwork() != 0)
+       {
+               OC_LOG(ERROR, TAG, "Unable to connect to network");
+               return;
+       }
+
+       // Initialize the OC Stack in Server mode
+       if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
+       {
+               OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+               return;
+       }
+
+    OCStartPresence(60);
+       // Declare and create the example resource: PROXI
+       createREFERResource();
+
+       ble.init( (long)115200, BLE_SLAVER,  REFER.m_macaddress);
+
+//     ble.StatusRead();
+
+       char str0[] = JSON_BASE00;
+       char str1[] = JSON_BASE01;
+       char str2[] = JSON_BASE02;
+       char str3[] = JSON_BASE03;
+
+       base_length = strlen(str0)+ strlen(str1)+ strlen(str2)+ strlen(str3);
+
+       OC_LOG_V(INFO, TAG, "Program Start-\r\n");
+}
+
+// The loop function is called in an endless loop
+void loop()
+{
+    // This artificial delay is kept here to avoid endless spinning
+    // of Arduino microcontroller. Modify it as per specfic application needs.
+
+    // This call displays the amount of free SRAM available on Arduino
+    PrintArduinoMemoryStats();
+       delay(5000);
+       if (OCProcess() != OC_STACK_OK)
+       {
+               OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+               return;
+       }
+       ChangeREFERRepresentation(NULL);
+
+       char* user_msg = NULL;
+       user_msg = ble.Debug2BLE( true );
+       ble.BLE2Debug( true );
+
+       if ( user_msg )
+       {
+               free( user_msg );
+               user_msg = NULL;
+       }
+}
+
+void createREFERResource() {
+
+    OCStackResult res = OCCreateResource(&REFER.m_handle,
+                                         "SoftSensorManager.Sensor",
+                                         "oc.mi.def",
+                                         "/Reference_Thing",
+                                         OCEntityHandlerCb,
+                                         OC_DISCOVERABLE|OC_OBSERVABLE);
+    OC_LOG_V(INFO, TAG, "Created REFER resource with result: %s", getResult(res));
+}
+
+const char *getResult(OCStackResult result) {
+    switch (result) {
+    case OC_STACK_OK:
+        return "OC_STACK_OK";
+    case OC_STACK_INVALID_URI:
+        return "OC_STACK_INVALID_URI";
+    case OC_STACK_INVALID_QUERY:
+        return "OC_STACK_INVALID_QUERY";
+    case OC_STACK_INVALID_IP:
+        return "OC_STACK_INVALID_IP";
+    case OC_STACK_INVALID_PORT:
+        return "OC_STACK_INVALID_PORT";
+    case OC_STACK_INVALID_CALLBACK:
+        return "OC_STACK_INVALID_CALLBACK";
+    case OC_STACK_INVALID_METHOD:
+        return "OC_STACK_INVALID_METHOD";
+    case OC_STACK_NO_MEMORY:
+        return "OC_STACK_NO_MEMORY";
+    case OC_STACK_COMM_ERROR:
+        return "OC_STACK_COMM_ERROR";
+    case OC_STACK_INVALID_PARAM:
+        return "OC_STACK_INVALID_PARAM";
+    case OC_STACK_NOTIMPL:
+        return "OC_STACK_NOTIMPL";
+    case OC_STACK_NO_RESOURCE:
+        return "OC_STACK_NO_RESOURCE";
+    case OC_STACK_RESOURCE_ERROR:
+        return "OC_STACK_RESOURCE_ERROR";
+    case OC_STACK_SLOW_RESOURCE:
+        return "OC_STACK_SLOW_RESOURCE";
+    case OC_STACK_NO_OBSERVERS:
+        return "OC_STACK_NO_OBSERVERS";
+    case OC_STACK_ERROR:
+        return "OC_STACK_ERROR";
+    default:
+        return "UNKNOWN";
+    }
+}
+
index 28cb319..fe41441 100644 (file)
@@ -58,9 +58,6 @@ typedef struct THRESOURCE
 
 static THResource TH;
 
-//char* g_responsePayloadPut =    "{\"href\":\"\",\"rep\":{\"0\":\"temperature\",\"1\":\"int\",\"2\":\"0\",\"3\":\"humidity\",\"4\":\"int\",\"5\":\"0\"}}";
-//char* g_responsePayloadGet =    "{\"href\":\"\",\"rep\":{\"0\":\"temperature\",\"1\":\"int\",\"2\":\"0\",\"3\":\"humidity\",\"4\":\"int\",\"5\":\"0\"}}";
-
 /// This is the port which Arduino Server will use for all unicast communication with it's peers
 static uint16_t OC_WELL_KNOWN_PORT = 5683;
 
@@ -71,23 +68,23 @@ static uint16_t OC_WELL_KNOWN_PORT = 5683;
 
 char temp[100];
 
-#define LENGTH_VAR      100
+#define LENGTH_VAR             100
 static int base_length = 0;
 
-bool JsonGenerator( THResource &th, char *jsonBuf, uint16_t buf_length )
+bool JsonGenerator( THResource& th, char* jsonBuf, uint16_t buf_length )
 {
-    if ( (buf_length - base_length) < LENGTH_VAR )
-    {
-        OC_LOG_V(ERROR, TAG, "Error : length is very long.");
-        return false;
-    }
+       if( (buf_length - base_length) < LENGTH_VAR )
+       {
+               OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+               return false;
+       }
 
-    sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%d", th.m_temp);
-    sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
+       sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%d",th.m_temp);
+       sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
 
-    Serial.println(jsonBuf);
+       Serial.println(jsonBuf);
 
-    return true;
+       return true;
 }
 
 byte read_dht11_dat()
@@ -196,46 +193,67 @@ void PrintArduinoMemoryStats()
 
 // This is the entity handler for the registered resource.
 // This is invoked by OCStack whenever it recevies a request for this resource.
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest *entityHandlerRequest )
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
 {
     OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCEntityHandlerResponse response = {0};
+    char payload[MAX_RESPONSE_LENGTH] = {0};
 
-    if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
     {
         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
-        if (OC_REST_GET == entityHandlerRequest->method)
+        if(OC_REST_GET == entityHandlerRequest->method)
         {
-            if (JsonGenerator( TH, (char *)entityHandlerRequest->resJSONPayload, \
-                               entityHandlerRequest->resJSONPayloadLen))
-            {
-            }
-            else
+               if(JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
+                {
+                }
+           else
             {
                 ehRet = OC_EH_ERROR;
             }
         }
-        if (OC_REST_PUT == entityHandlerRequest->method)
+        if(OC_REST_PUT == entityHandlerRequest->method)
         {
             //Do something with the 'put' payload
-            if (JsonGenerator( TH, (char *)entityHandlerRequest->resJSONPayload, \
-                               entityHandlerRequest->resJSONPayloadLen))
+            if (JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
             {
             }
             else
             {
                 ehRet = OC_EH_ERROR;
             }
-        }
+         }
+
+        if (ehRet == OC_EH_OK)
+               {
+                       // Format the response.  Note this requires some info about the request
+                       response.requestHandle = entityHandlerRequest->requestHandle;
+                       response.resourceHandle = entityHandlerRequest->resource;
+                       response.ehResult = ehRet;
+                       response.payload = (unsigned char *)payload;
+                       response.payloadSize = strlen(payload);
+                       response.numSendVendorSpecificHeaderOptions = 0;
+                       memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+                       memset(response.resourceUri, 0, sizeof response.resourceUri);
+                       // Indicate that response is NOT in a persistent buffer
+                       response.persistentBufferFlag = 0;
+
+                       // Send the response
+                       if (OCDoResponse(&response) != OC_STACK_OK)
+                       {
+                               OC_LOG(ERROR, TAG, "Error sending response");
+                               ehRet = OC_EH_ERROR;
+                       }
+               }
     }
     if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
     {
-        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action)
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
         {
             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
             g_THUnderObservation = 1;
         }
-        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
         {
             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
         }
@@ -301,7 +319,7 @@ void *ChangeTHRepresentation (void *param)
         TH.m_humid = dht11_dat[0];
         TH.m_temp = dht11_dat[2];
 
-        if (g_THUnderObservation)
+           if (g_THUnderObservation)
         {
             OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.m_humid);
             OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.m_temp);
@@ -344,7 +362,7 @@ void setup()
         OC_LOG(ERROR, TAG, PCF("OCStack init error"));
         return;
     }
-
+    OCStartPresence(60);
     // Declare and create the example resource: TH
     createTHResource();
 
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile
new file mode 100644 (file)
index 0000000..d21b780
--- /dev/null
@@ -0,0 +1,130 @@
+# //******************************************************************
+# //
+# // Copyright 2014 Intel Mobile Communications GmbH 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 ../../../../build/arduino/environment.mk
+ARDUINO_DIR = /usr/share/arduino
+
+BUILD := release
+PLATFORM := arduinomega
+ARDUINO_PORT := ttyACM0
+
+SRCLIST=${wildcard ${SRC_PATH}/*.cpp}
+OBJPATH=${SRCLIST:.cpp=.o}
+OBJLIST=${notdir ${OBJPATH}}
+
+SRC_PATH=../src
+# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
+ARDUINOWIFI := 0
+
+APP_NAME := trackee
+
+TB_DIR = ../../../../../../resource/csdk
+LOGGER_DIR = $(TB_DIR)/logger
+OC_LOG_DIR = $(TB_DIR)/../oc_logger
+TBSTACK_DIR = $(TB_DIR)/stack
+TBSOCKET_DIR = $(TB_DIR)/ocsocket
+
+include $(TB_DIR)/local.properties
+include $(TB_DIR)/$(PLATFORM).properties
+
+VPATH := $(SDIR_ARD_PLATFORM)
+
+#include directories
+OCSOCK_DIR = $(TB_DIR)/ocsocket
+LOGGER_DIR = $(TB_DIR)/logger
+STACK_DIR  = $(TB_DIR)/stack
+INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include -I../include
+
+CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
+CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
+
+CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
+
+ifeq ($(ARDUINOWIFI),1)
+       CFLAGS += -DARDUINOWIFI
+       ARDUINO_SHIELD_TYPE := "/wifi_shield"
+       TRANSPORT_OBJS = $(WIFI_COBJ)
+else
+       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
+       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
+endif
+
+OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
+
+OBJ_DIR := $(OUT_DIR)/bin
+
+all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
+
+core.a: $(PLATFORM_OBJS)
+       @cd $(OBJ_DIR) && $(AR) -x ../../../../$(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a
+       $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o
+       @cd $(OBJ_DIR) && $(RANLIB) $@
+
+prep_dirs:
+       -mkdir $(PLATFORM)
+       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
+       -mkdir $(OUT_DIR)
+       -mkdir $(OBJ_DIR)
+
+%.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+%.o: %.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
+%.o: ${SRC_PATH}/%.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+$(APP_NAME).elf: $(OBJLIST) core.a
+ifeq ($(PLATFORM),arduinomega)
+       $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@
+else ifeq ($(PLATFORM),arduinodue)
+       $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+$(APP_NAME).hex: $(APP_NAME).elf
+ifeq ($(PLATFORM),arduinomega)
+       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep
+       $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@
+else ifeq ($(PLATFORM),arduinodue)
+       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+install: all
+ifeq ($(PLATFORM),arduinomega)
+       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i
+else ifeq ($(PLATFORM),arduinodue)
+       stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb
+       $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+.PHONY: clean
+
+clean: legacy_clean
+       rm -rf arduinomega
+       rm -rf arduinodue
+
+legacy_clean:
+       @rm -rf bin
+       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h
new file mode 100644 (file)
index 0000000..8356098
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * bleLib.h
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#ifndef BLELIB_H_
+#define BLELIB_H_
+
+#include "Arduino.h"
+
+#define BLE_NOCHANGE   -1
+#define BLE_MASTER             1
+#define BLE_SLAVER             0
+
+#define BLE_DISCON             200
+#define BLE_NODATA             100
+
+
+/***************************************
+ *
+ *     HM-10 BLE Module Control Class.
+ *     Target Board : Arduino-Mega.
+ *
+ **************************************/
+class Cble
+{
+public :
+       /***
+        * BLE Control Function.
+        */
+       // BLE initialization ( COM baud rate , BLE Master , Slave setting. )
+       void init(long baudRate, int ble_mode, char* SelfMaxAddr);
+
+       void StatusRead( void );
+
+       bool IsSelfArduino( void );
+
+       bool IsConnected( void );
+
+       bool pollingConnect( const char* maxAddr );
+
+       void pollingDisconnect( void );
+       // Get RSSI by BLE communication. (polling method.)
+       int pollingGetRSSI( void );
+       // Send Request to BLE Module. And, Get the response. (polling method.)
+       bool pollingRequest(const char* request, char* data, int dataLen);
+
+       int mustHaveRequest(const char* request, char* data, int dataLen);
+
+       void streamDummy( char* data, int dataLen);
+
+       /***
+        * Debug COM port to BLE COM port.
+        * BLE COM port to Debug COM port.
+        */
+       // BLE Module to Debug Serial port.
+       void BLE2Debug( int autoDiscon );
+       // Debug Serial port to BLE Module.
+       char* Debug2BLE( int BLEwrite );
+
+       /***
+        * If you first setting, you need next-function.
+        */
+       // Restore to factory setting data.
+       void FactoryReset( void );
+       // First setting of COM port.
+       void firstUartSetting( void );
+};
+
+
+
+#if 0
+#define debug_printf(...)      {                                                       \
+       char* __temp__ = (char*)malloc(sizeof(char)*2048);              \
+       sprintf(__temp__, __VA_ARGS__ );                                        \
+       Serial.print(__temp__);                                                                 \
+       free(__temp__);                                                                                                 \
+}
+#else
+#define debug_printf(...)
+#endif
+
+
+
+#endif /* BLELIB_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/oic_lanLib.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/oic_lanLib.h
new file mode 100644 (file)
index 0000000..41556f6
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * oic_lanLib.h
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#ifndef OIC_LANLIB_H_
+#define OIC_LANLIB_H_
+
+
+int ConnectToNetwork();
+
+
+#endif /* OIC_WIFILIB_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h
new file mode 100644 (file)
index 0000000..8e8666a
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * proximity.h
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#ifndef PROXIMITY_H_
+#define PROXIMITY_H_
+
+
+#define arraysize      6
+#define RSSI_EA                3
+
+float CalculateExponentialAverage(int numberOfSamples, int* array, int startindex, int flag);
+
+float calculateDistance(float avgRSSI, float txPower);
+
+#endif /* PROXIMITY_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h
new file mode 100644 (file)
index 0000000..4271904
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * trackee.h
+ *
+ *  Created on: 2014. 11. 18.
+ *      Author: eunseok
+ */
+
+#ifndef TRACKEE_H_
+#define TRACKEE_H_
+
+
+#define ARDUINO                0
+
+
+#endif /* TRACKEE_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp
new file mode 100644 (file)
index 0000000..31cf5da
--- /dev/null
@@ -0,0 +1,586 @@
+/*
+ * blsLib.cpp
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#include "bleLib.h"
+#include <stdarg.h>
+#include "trackee.h"
+
+//#define __INTERNAL_DEBUG__           1
+
+PROGMEM const char TAG[] = "TrackeeSensor";
+#define LIMIT_COUNT                    100
+#define DUMMY_SIZE                     30
+#define DEBUG_SIZE                     DUMMY_SIZE
+#if (ARDUINO != 0)
+#define SERIAL_SIZE                    100
+#endif
+
+#define BLE            Serial2
+
+bool isConnected = false;
+int SerialCnt=0;
+int BLECnt=0;
+char SelfMaxaddr[19] = {0,};
+
+char debugD[DEBUG_SIZE]={0,};
+
+#if (ARDUINO != 0)
+char SerialData[SERIAL_SIZE]={0,};
+char BLEData[SERIAL_SIZE]={0,};
+#endif
+
+// baudRate이 115200이면, 주의해야한다.
+// Arduino Chip은 16bit Process 이므로 int형의 사이즈가 4byte형 signed int이다.
+void Cble::init(long baudRate, int ble_mode, char* SelfMaxAddr)
+{
+       debug_printf("BLE shiled is initialed.-\r\n");
+
+       if(SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE )
+       {
+               debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n");
+               exit(-1);
+       }
+       sprintf(SelfMaxaddr, "%s",SelfMaxAddr);
+
+       BLE.begin(baudRate);
+       BLE.setTimeout(1);
+       delay(1000);
+
+       memset(debugD,0,DEBUG_SIZE);
+
+       if( ble_mode != BLE_NOCHANGE )
+       {
+               while( IsSelfArduino() == false )
+                       this->pollingDisconnect();
+       }
+
+       if( ble_mode == BLE_MASTER )
+       {
+               pollingRequest("AT+ROLE1", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+MODE0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+NOTI0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+       }
+       else if ( ble_mode == BLE_SLAVER )
+       {
+               pollingRequest("AT+ROLE0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+MODE2", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+               delay(150);
+               pollingRequest("AT+NOTI0", debugD, 8);
+               memset(debugD, 0, DEBUG_SIZE);
+       }
+
+       if( ble_mode != BLE_NOCHANGE )
+       {
+               while( IsSelfArduino() == false )
+                       this->pollingDisconnect();
+       }
+
+       delay(250);
+}
+
+void Cble::StatusRead( void )
+{
+       debug_printf("StatusRead function called.\r\n");
+
+       pollingRequest("AT+ROLE?", debugD, 9);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+MODE?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+IMME?", debugD, 9);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+TYPE?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+POWE?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+NOTI?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+       pollingRequest("AT+PIO1?", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+       delay(150);
+}
+
+bool Cble::IsConnected( void )
+{
+       return isConnected;
+}
+
+bool Cble::IsSelfArduino( void )
+{
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("IsSelfArduino is called.\r\n");
+#endif
+       int length=mustHaveRequest("AT+ADDR?", debugD, 20);
+
+       if( strstr(debugD, SelfMaxaddr) )
+       {
+               isConnected = false;
+               memset(debugD,0,length);
+               return true;
+       }
+       else
+       {
+               isConnected = true;
+               memset(debugD,0,length);
+               return false;
+       }
+}
+
+bool Cble::pollingConnect( const char* maxAddr )
+{
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("pollingConnect is called.\r\n");
+#endif
+
+#define CONNECT_SIZE           20
+
+       char cmd[CONNECT_SIZE]= {0,};
+
+       // is Connected Address ?
+       pollingRequest("AT+ADDR?", debugD, 20);
+       if( strstr(debugD, maxAddr) )
+       {
+               isConnected = true;
+               memset(debugD,0,DEBUG_SIZE);
+               return isConnected;
+       }
+       memset(debugD,0,DEBUG_SIZE);
+
+       // Try Connection.
+       sprintf(cmd, "AT+CON%s",maxAddr);
+       if( pollingRequest(cmd, debugD, 8) == false )
+       {
+               debug_printf("Error : %s command is failed.\r\n",cmd );
+               memset(debugD,0,DEBUG_SIZE);
+               pollingDisconnect();
+               return false;
+       }
+       else if( strstr(debugD,"OK+CONNA") )
+       {
+               isConnected = true;
+               memset(debugD,0,DEBUG_SIZE);
+       }
+       else
+       {
+               memset(debugD,0,DEBUG_SIZE);
+               pollingDisconnect();
+               return false;
+       }
+       // Confirm Connected Address.
+       pollingRequest("AT+ADDR?", debugD, 20);
+
+       if( strstr(debugD, maxAddr) == 0 )
+       {
+               isConnected = false;
+               if ( strstr(debugD, "OK+CONNF") )
+               {
+                       memset(debugD,0,DEBUG_SIZE);
+                       streamDummy(debugD, 8);
+               }
+       }
+       memset(debugD,0,DEBUG_SIZE);
+       delay(5);
+
+       return isConnected;
+
+#undef CONNECT_SIZE
+}
+
+
+#define  CMD_DISCONNECT                "(CMD_DISCON)"
+void Cble::pollingDisconnect( void )
+{
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("pollingDisconnect is called.\r\n");
+#endif
+       int length=0;
+#if (ARDUINO == 0)
+       pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL);
+       delay(5);
+
+       length=mustHaveRequest("AT", debugD, 2);
+       if( strstr(debugD,"OK") )
+               isConnected = false;
+
+       memset(debugD,0,length);
+#else
+       if( BLE.available() )
+       {
+               if( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true )
+               {
+                       debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT);
+
+                       do {
+                               debug_printf("pollingDisconnect : Send AT message.\r\n");
+                               if( length )
+                                       memset(debugD, 0, length);
+
+                               length=mustHaveRequest("AT", debugD, 2);
+                       }while( strstr(debugD,"OK") == NULL );
+
+                       debug_printf("pollingDisconnect() is Success.\r\n");
+                       memset(debugD, 0, length);
+               }
+       }
+#endif
+
+       delay(5);
+}
+
+int Cble::pollingGetRSSI( void )
+{
+#define RSSI_SIZE              11
+#define RSSI_POS               7
+
+       long time_cnt=0;
+       char c=0;
+       char index=0;
+       char rssi_res[RSSI_SIZE] = {0,};
+
+       streamDummy(NULL, NULL);
+
+       if( isConnected == true )
+       {
+               BLE.write("AT+RSSI?");
+               BLE.flush();
+               delay(5);
+
+               while(1)
+               {
+                       if ( BLE.available() )
+                               c = (char)BLE.read();
+                       else
+                       {
+                               c = 0;
+                               time_cnt++;
+                       }
+
+                       if( c )
+                       {
+                               rssi_res[index] = c;
+                               index++;
+                               if( index == RSSI_SIZE-1 )
+                               {
+                                       rssi_res[index] = '\0';
+                                       goto RESULT;
+                               }
+                       }
+
+       //              debug_printf("time_cnt=%d\r\n", time_cnt);
+                       if( time_cnt == 0xFFFFF )
+                       {
+                               debug_printf("Error : Time Out GetRSSI().\r\n");
+                               return BLE_NODATA;
+                       }
+
+               }
+
+       RESULT :
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("res= %s \r\n",rssi_res);
+#endif
+               char* Srssi = &(rssi_res[RSSI_POS]);
+       //      debug_printf("[S] rssi=%s\r\n", Srssi);
+               int rssi = atoi(Srssi);
+       //      debug_printf("rssi=%d\r\n", rssi);
+
+               return rssi;
+       }
+
+       return BLE_DISCON;
+
+#undef RSSI_POS
+#undef RSSI_SIZE
+}
+
+int Cble::mustHaveRequest(const char* request, char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       BLE.write(request);
+       BLE.flush();
+       delay(150);
+
+READ_STREAM :
+       while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+       {
+               cnt++;
+               delay(10);
+
+               if ( cnt >= LIMIT_COUNT/10 )
+               {
+#ifdef __INTERNAL_DEBUG__
+                       debug_printf("=====> Retry Request command Send. <=========\r\n");
+#endif
+                       cnt = 0;
+                       BLE.write(request);
+                       BLE.flush();
+
+                       required_length = dataLen;
+                       data_index = data;
+                       length = 0;
+                       delay(50);
+               }
+       }
+
+       required_length -= length;
+       if( required_length != 0 )
+       {
+               data_index = data_index + length;
+               length = 0;
+               goto READ_STREAM;
+       }
+
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       return dataLen;
+}
+
+bool Cble::pollingRequest(const char* request, char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       BLE.write(request);
+       BLE.flush();
+
+       if( data_index )
+       {
+               delay(250);
+
+READ_STREAM :
+               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+               {
+                       cnt++;
+                       if ( cnt >= LIMIT_COUNT )
+                       {
+                               debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request);
+                               return false;
+                       }
+               }
+
+               required_length -= length;
+               if( required_length != 0 )
+               {
+                       data_index = data_index + length;
+                       length = 0;
+                       goto READ_STREAM;
+               }
+
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       }
+       return true;
+}
+
+void Cble::streamDummy( char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       if( data && required_length )
+       {
+READ_STREAM :
+               while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+               {
+                       cnt++;
+                       if ( cnt >= LIMIT_COUNT )
+                       {
+                               debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n");
+                               return ;
+                       }
+               }
+
+               required_length -= length;
+               if( required_length != 0 )
+               {
+                       data_index = data_index + length;
+                       length = 0;
+                       goto READ_STREAM;
+               }
+
+               debug_printf("[ streamDummy ] %s\r\n\r\n", data);
+       }
+       else
+       {
+               if( BLE.available() )
+               {
+                       BLE.readBytes(debugD, DEBUG_SIZE);
+#ifdef __INTERNAL_DEBUG__
+                       debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
+#endif
+                       memset(debugD, 0, DEBUG_SIZE);
+               }
+       }
+
+}
+
+#if (ARDUINO != 0)
+
+#define REGARD_DISCON                  5000
+int needDiscon = 0;
+unsigned long global_cnt = 0;
+
+void Cble::BLE2Debug( int autoDiscon )
+{
+       int cnt=0;
+       uint8_t length=0;
+
+       if( BLE.available() )
+       {
+               while( (length=BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 )
+               {
+                       cnt++;
+                       if ( cnt >= LIMIT_COUNT )
+                               return ;
+               }
+
+               global_cnt = 0;
+               needDiscon = 0;
+
+               Serial.println(BLEData);
+               memset(BLEData, 0, length);
+       }
+       else if ( autoDiscon )
+       {
+               global_cnt++;
+//             debug_printf("global_cnt=%u , ", global_cnt );
+//             debug_printf("needDiscon=%d\r\n", needDiscon);
+               if( !needDiscon && global_cnt >= REGARD_DISCON )
+               {
+                       needDiscon = 1;
+                       debug_printf("result : global_cnt=%u , ", global_cnt );
+                       debug_printf("needDiscon=%d\r\n", needDiscon);
+               }
+
+               if ( needDiscon )
+               {
+                       debug_printf("Auto Discon : global_cnt=%u , ", global_cnt );
+                       debug_printf("needDiscon=%d\r\n", needDiscon);
+                       if( pollingRequest("AT", debugD, 2) == true )
+                       {
+                               global_cnt = 0;
+                               needDiscon = 0;
+                       }
+               }
+       }
+}
+
+char* Cble::Debug2BLE( int BLEwrite )
+{
+       char* result = NULL;
+
+       if( Serial.available() )
+       {
+               char c = (char)Serial.read();
+
+               switch(c)
+               {
+               case '\0':
+                       return result;
+               case '\r':
+               case '\n':
+                       debug_printf("\r\n");
+                       if(BLEwrite && SerialCnt)
+                       {
+                               BLE.write(SerialData);
+                               BLE.flush();
+                       }
+
+                       result = (char*)malloc(sizeof(char)*(SerialCnt+1));
+                       memcpy(result, SerialData, SerialCnt );
+                       result[SerialCnt] = NULL;
+
+                       memset(SerialData, 0, SerialCnt+1);
+                       SerialCnt=0;
+                       break;
+               default :
+                       SerialData[SerialCnt] = c;
+                       SerialCnt++;
+                       Serial.print(c);
+                       break;
+               }
+       }
+
+       return result;
+}
+#else
+void Cble::BLE2Debug( int autoDiscon )
+{
+       ;
+}
+
+char* Cble::Debug2BLE( int BLEwrite )
+{
+        return NULL;
+}
+#endif
+
+void Cble::FactoryReset( void )
+{
+       debug_printf("FactoryReset is called.\r\n");
+
+       pollingRequest("AT+RENEW", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+}
+
+
+void Cble::firstUartSetting( void )
+{
+       debug_printf("firstUartSetting is called.\r\n");
+
+       Serial.begin(9600);
+       BLE.begin(9600);
+       BLE.setTimeout(1);
+       delay(1000);
+
+       pollingRequest("AT+BAUD4", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+
+       debug_printf("Please Power off and on.\r\n");
+       BLE.end();
+//     delay(1000);
+//
+//     BLE.begin(115200);
+//     delay(1000);
+//
+//     pollingRequest("AT", debugD, DEBUG_SIZE);
+//     memset(debugD, 0, DEBUG_SIZE);
+
+
+       exit(0);
+}
+
+
+
+
+
+
+
+
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp
new file mode 100644 (file)
index 0000000..432ee0d
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * oic_wifiLib.cpp
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+// proximity code e
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+
+PROGMEM const char TAG[] = "TrackeeSensor";
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+
+/// WiFi Shield firmware with Intel patches
+static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
+
+/// WiFi network info and credentials
+char ssid[] = "SoftSensor_AP";
+char pass[] = "1234567890";
+//char ssid[] = "SoftSensor_2.4G";
+//char pass[] = "12344321";
+
+int ConnectToNetwork()
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
+        return -1;
+    }
+
+    // Verify that WiFi Shield is running the firmware with all UDP fixes
+    fwVersion = WiFi.firmwareVersion();
+    OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
+    if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
+    {
+        OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        return -1;
+    }
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED)
+    {
+        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+        status = WiFi.begin(ssid,pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+    }
+    OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
+
+    IPAddress ip = WiFi.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#else
+// Arduino Ethernet Shield
+int ConnectToNetwork()
+{
+    // Note: ****Update the MAC address here with your shield's MAC address****
+    uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAC};
+
+    uint8_t error = Ethernet.begin(ETHERNET_MAC);
+    if (error  == 0)
+    {
+        OC_LOG_V(ERROR, TAG, "error is: %d", error);
+        return -1;
+    }
+    IPAddress ip = Ethernet.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#endif //ARDUINOWIFI
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp
new file mode 100644 (file)
index 0000000..351f930
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * proximity.cpp
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#include "Arduino.h"
+#include "proximity.h"
+#include <math.h>
+
+// Proximity code start
+float CalculateExponentialAverage(int numberOfSamples, int* array, int startindex, int flag){
+       float numerator = 0;
+       float denominator = 0;
+
+       float average = 0.0;
+
+       if (flag < arraysize / RSSI_EA)   // first loop buffer full
+       {
+               for (int i = 0; i < startindex; i++)
+               {
+                       average += array[i];
+               }
+               if(startindex == 0){}
+               else{
+                       average = average / startindex;
+               }
+
+               Serial.print("average1 : ");
+               Serial.println(average);
+       }
+       else
+       {
+               for (int i = 0; i < arraysize; i++)
+               {
+                       average += array[i];
+               }
+
+               for (int i = startindex; i < startindex + RSSI_EA; i++)
+               {
+                       average -= array[i];
+               }
+               average = average / (arraysize - numberOfSamples);
+
+               Serial.print("average2 : ");
+               Serial.println(average);
+       }
+       //exponential moving average
+       int i = 0;
+       //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT
+       float beta=0.8f;
+       for (i = startindex + numberOfSamples - 1; i >= startindex; i--)
+       {
+               numerator += array[i]* pow(beta, startindex + numberOfSamples - i - 1);
+               denominator += pow(beta, startindex + numberOfSamples - i - 1);
+       }
+
+       int offset = 3;
+       if(average != 0.0){
+         numerator += average * pow(beta, offset + numberOfSamples);
+         denominator += pow(beta, offset + numberOfSamples);
+       }
+       return numerator / denominator;
+}
+
+
+float calculateDistance(float avgRSSI, float txPower)
+{
+       if (avgRSSI == 0)
+       {
+               return -1.0;
+       }
+
+       float ratio = avgRSSI*1.0/txPower;
+       if (ratio < 1.0)
+       {
+               return pow(ratio,10);
+       }
+       else
+       {
+               float distance =  (0.7)*pow(ratio,10) + 0.024;
+               return distance;
+       }
+}
+
+// proximity code end
+
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/readme.txt b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/readme.txt
new file mode 100644 (file)
index 0000000..7c041e1
--- /dev/null
@@ -0,0 +1,19 @@
+
+Followings should be done befor building Arudno applications 
+
+1. Applications on arduino conform  the Iotivity Base released on 22-Aug-2014.
+   (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
+
+   For successful execution, you have to copy the file, local.properties, into the following pathes:
+    - oic-resource/csdk/
+    - oic-resource/csdk/libcoap-4.1.1
+
+
+2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
+
+   Makefile path:  / oic-resource / csdk / libcoap-4.1.1 / makefile
+
+   path to be modified: 
+  
+     - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
+     - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
\ No newline at end of file
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp
new file mode 100644 (file)
index 0000000..8d78c5b
--- /dev/null
@@ -0,0 +1,443 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+
+
+// Do not remove the include below
+#include "Arduino.h"
+#include "bleLib.h"
+#include <stdio.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "oic_lanLib.h"
+#include "trackee.h"
+
+// proximity code s
+#define DATA_EA                400
+#define SLAVER_EA      2
+
+#define ARDUINO_AVR_MEGA2560 1
+/// This is the port which Arduino Server will use for all unicast communication with it's peers
+#define OC_WELL_KNOWN_PORT 5683
+
+PROGMEM const char TAG[] = "TrackeeSensor";
+
+OCResourceHandle m_handle;             // OIC base를 handling하기위해서 필요한 handler.
+
+#if (ARDUINO == 0)
+#include "proximity.h"
+
+#define JSON_BASE "{\"href\":\"\",\"rep\":{"
+#define JSON_BASE00 "\"0\":\"trackeeID\",\"1\":\"string\",\"2\":\""
+#define JSON_BASE01 "\",\"3\":\"things\",\"4\":\"int\",\"5\":\""
+#define JSON_BASE02 "\",\"6\":\"ID\",\"7\":\"string\",\"8\":\""
+#define JSON_BASE03 "\",\"9\":\"distance\",\"10\":\"float\",\"11\":\""
+#define JSON_BASE04 "\",\"12\":\"proximity\",\"13\":\"int\",\"14\":\""
+#define JSON_BASE05 "\",\"15\":\"SD\",\"16\":\"float\",\"17\":\""
+#define JSON_BASE06 "\",\"18\":\"ID\",\"19\":\"string\",\"20\":\""
+#define JSON_BASE07 "\",\"21\":\"distance\",\"22\":\"float\",\"23\":\""
+#define JSON_BASE08 "\",\"24\":\"proximity\",\"25\":\"int\",\"26\":\""
+#define JSON_BASE09 "\",\"27\":\"SD\",\"28\":\"float\",\"29\":\""
+#define JSON_BASE10 "\"}}"
+
+typedef struct PROXIRESOURCE {
+    float m_distance[SLAVER_EA];
+    float m_proximity[SLAVER_EA];
+} PROXIResource;
+
+PROXIResource PROXI;
+
+int rssi[SLAVER_EA][arraysize];
+int rssicnt[SLAVER_EA] = {0,};
+int startindex[SLAVER_EA] = {0,};
+int flag[SLAVER_EA] = {0,};
+//#else
+//bool bleWrite = true;
+#endif
+
+Cble ble;
+
+char trackeeID[13] = "9059AF16FEF7";
+int slaver_num = 0;
+
+char slaveList[SLAVER_EA][13]={"9059AF1700EE","34B1F7D004D2"};
+int g_PROXIUnderObservation = 0;
+
+
+
+const char *getResult(OCStackResult result);
+void createResource();
+
+
+#define LENGTH_VAR             50
+bool JsonGenerator( char* jsonBuf, uint16_t buf_length )
+{
+       if( g_PROXIUnderObservation == 1 )
+       {
+#if (ARDUINO == 0)
+               PROXIResource* ref = &PROXI;
+               int ref_cnt = SLAVER_EA;
+               uint16_t base_length = 0;
+               base_length = strlen(JSON_BASE)+ strlen(JSON_BASE00)+ strlen(JSON_BASE01)+ strlen(JSON_BASE02)+ strlen(JSON_BASE03)+\
+                                     strlen(JSON_BASE04)+ strlen(JSON_BASE05)+ strlen(JSON_BASE06)+ strlen(JSON_BASE07)+\
+                                     strlen(JSON_BASE08)+ strlen(JSON_BASE09)+ strlen(JSON_BASE10);
+
+               OC_LOG_V(INFO, TAG, "base length = %d, buf_length=%d", base_length, buf_length );
+
+               if( ((long)buf_length - (long)base_length) < LENGTH_VAR )
+               {
+                       OC_LOG_V(ERROR, TAG, "Error : length is very long.");
+                       return false;
+               }
+
+               sprintf(jsonBuf, JSON_BASE );
+               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE00"%s"JSON_BASE01"%d", trackeeID, ref_cnt);
+               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03"%d.%03d", slaveList[0], (int)ref->m_distance[0], (int)((ref->m_distance[0]-(int)ref->m_distance[0])*1000.0) );
+               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE04"%d"JSON_BASE05"0.0", (int)ref->m_proximity[0] );
+               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE06"%s"JSON_BASE07"%d.%03d", slaveList[1], (int)ref->m_distance[1], (int)((ref->m_distance[1]-(int)ref->m_distance[1])*1000.0) );
+               sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE08"%d"JSON_BASE09"0.0", (int)ref->m_proximity[1] );
+               strcpy(jsonBuf+strlen(jsonBuf), JSON_BASE10 );
+
+               OC_LOG_V(INFO, TAG, "json length = %u", strlen(jsonBuf) );
+
+               return true;
+
+#else          // Slave Json Code.
+
+               return true;
+#endif
+       }
+
+       OC_LOG_V(INFO, TAG, "Not Support Observer unfounded mode." );
+       return false;
+}
+
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+    //This var is declared in avr-libc/stdlib/malloc.c
+    //It keeps the largest address not allocated for heap
+    extern char *__brkval;
+    //address of tmp gives us the current stack boundry
+    int tmp;
+    OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+    OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+             ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+
+// This is the entity handler for the registered resource.
+// This is invoked by OCStack whenever it recevies a request for this resource.
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
+{
+    OCEntityHandlerResult ehRet = OC_EH_OK;
+    OCEntityHandlerResponse response = {0};
+    char payload[MAX_RESPONSE_LENGTH] = {0};
+
+    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+        if(OC_REST_GET == entityHandlerRequest->method)
+        {
+                if(JsonGenerator(payload, MAX_RESPONSE_LENGTH))
+                {
+                }
+           else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        if(OC_REST_PUT == entityHandlerRequest->method)
+        {
+            //Do something with the 'put' payload
+            if (JsonGenerator(payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+         }
+    }
+
+    if (ehRet == OC_EH_OK)
+   {
+          // Format the response.  Note this requires some info about the request
+          response.requestHandle = entityHandlerRequest->requestHandle;
+          response.resourceHandle = entityHandlerRequest->resource;
+          response.ehResult = ehRet;
+          response.payload = (unsigned char *)payload;
+          response.payloadSize = strlen(payload);
+          response.numSendVendorSpecificHeaderOptions = 0;
+          memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+          memset(response.resourceUri, 0, sizeof response.resourceUri);
+          // Indicate that response is NOT in a persistent buffer
+          response.persistentBufferFlag = 0;
+
+          // Send the response
+          if (OCDoResponse(&response) != OC_STACK_OK)
+          {
+                  OC_LOG(ERROR, TAG, "Error sending response");
+                  ehRet = OC_EH_ERROR;
+          }
+    }
+
+    if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
+    {
+        if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
+            g_PROXIUnderObservation = 1;
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
+        }
+    }
+    return ehRet;
+}
+
+
+#if (ARDUINO == 0)
+void ChangePROXIRepresentation (void *param)
+{
+       (void)param;
+       OCStackResult result = OC_STACK_ERROR;
+       float avg[SLAVER_EA] = {0,};
+
+       for(int i = 0; i < SLAVER_EA; i++)
+       {
+                 if( rssicnt[i] > arraysize - 1)
+                 {
+                       rssicnt[i] = rssicnt[i] % arraysize;
+                 }
+
+               ble.streamDummy(NULL, NULL);
+
+               while(ble.pollingConnect(&slaveList[slaver_num][0]) == false){
+                       ble.streamDummy(NULL, NULL);
+               }
+
+               if( ble.IsConnected() == true )
+               {
+                       // print the string when a newline arrives:
+                       OC_LOG_V(INFO, TAG, "Connected. (%s)\r\n", slaveList[slaver_num]);
+
+                       for(int j=0; j < RSSI_EA; j++){
+                               rssi[i][rssicnt[i]] = ble.pollingGetRSSI();
+                               OC_LOG_V(INFO, TAG, "rssi val : %d \r\n", rssi[i][rssicnt[i]]);
+                          rssicnt[i]++;
+                       }
+
+                       while( ble.IsSelfArduino() == false )
+                               ble.pollingDisconnect();
+
+                       slaver_num++;
+                       slaver_num = slaver_num % SLAVER_EA;
+               }
+
+               avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]);
+               Serial.println(avg[i]);
+               Serial.print("distance : ");
+
+               PROXI.m_distance[i] = calculateDistance(avg[i], -58);
+
+               if(PROXI.m_distance[i] <= 1){
+                       PROXI.m_proximity[i] = 1;
+               }
+               else if(PROXI.m_distance[i] <= 2){
+                       PROXI.m_proximity[i] = 2;
+               }
+               else{
+                       PROXI.m_proximity[i] = 3;
+               }
+
+               Serial.println(PROXI.m_distance[i]);
+               Serial.println(PROXI.m_proximity[i]);
+
+               startindex[i] += RSSI_EA;
+
+               // This call displays the amount of free SRAM available on Arduino
+               PrintArduinoMemoryStats();
+
+               if(startindex[i] >= arraysize){
+                       startindex[i] = 0;
+               }
+
+               if(flag[i] < (arraysize / RSSI_EA))
+               {
+                       flag[i]++;
+               }
+       }
+
+       result = OCNotifyAllObservers (m_handle, OC_NA_QOS);
+
+       if (OC_STACK_NO_OBSERVERS == result)
+       {
+               OC_LOG_V(INFO, TAG, "g_PROXIUnderObservation is 0." );
+               g_PROXIUnderObservation = 0;
+       }
+
+}
+#endif
+
+
+
+
+//The setup function is called once at startup of the sketch
+void setup()
+{
+       Serial.begin(115200);
+
+       // Add your initialization code here
+       OC_LOG_INIT();
+
+       OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
+       //    uint16_t port = OC_WELL_KNOWN_PORT;
+
+       // Connect to Ethernet or WiFi network
+       if (ConnectToNetwork() != 0)
+       {
+               OC_LOG(ERROR, TAG, "Unable to connect to network");
+               return;
+       }
+
+       // Initialize the OC Stack in Server mode
+       if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
+       {
+               OC_LOG(ERROR, TAG, PCF("OCStack init error"));
+               return;
+       }
+
+    OCStartPresence(60);
+       // Declare and create the example resource
+       createResource();
+
+       // This call displays the amount of free SRAM available on Arduino
+       PrintArduinoMemoryStats();
+#if (ARDUINO == 0)
+       ble.init( (long)115200, BLE_MASTER, trackeeID);
+#elif (ARDUINO == 1)
+       ble.init( (long)115200, BLE_SLAVER, slaveList[0]);
+#elif (ARDUINO == 2)
+       ble.init( (long)115200, BLE_SLAVER, slaveList[1]);
+#endif
+
+//     ble.StatusRead();
+
+       OC_LOG_V(INFO, TAG, "Program Start-\r\n");
+}
+
+
+// The loop function is called in an endless loop
+void loop()
+{
+    // This artificial delay is kept here to avoid endless spinning
+    // of Arduino microcontroller. Modify it as per specfic application needs.
+
+       if (OCProcess() != OC_STACK_OK)
+       {
+               OC_LOG(ERROR, TAG, PCF("OCStack process error"));
+               return;
+       }
+#if (ARDUINO == 0)
+       ChangePROXIRepresentation(NULL);
+#else
+       char* user_cmd = NULL;
+
+//     ble.pollingDisconnect();
+
+       user_cmd = ble.Debug2BLE(true);
+       ble.BLE2Debug( true );
+
+       if( user_cmd )
+       {
+               free( user_cmd );
+               user_cmd = NULL;
+       }
+
+#endif
+}
+
+
+
+
+
+
+
+void createResource() {
+
+    OCStackResult res = OCCreateResource(&m_handle,
+                                         "SoftSensorManager.Sensor",
+                                         "oc.mi.def",
+                                         "/Tracker_Thing",
+                                         OCEntityHandlerCb,
+                                         OC_DISCOVERABLE|OC_OBSERVABLE);
+    OC_LOG_V(INFO, TAG, "Created PROXI resource with result: %s", getResult(res));
+}
+
+const char *getResult(OCStackResult result) {
+    switch (result) {
+    case OC_STACK_OK:
+        return "OC_STACK_OK";
+    case OC_STACK_INVALID_URI:
+        return "OC_STACK_INVALID_URI";
+    case OC_STACK_INVALID_QUERY:
+        return "OC_STACK_INVALID_QUERY";
+    case OC_STACK_INVALID_IP:
+        return "OC_STACK_INVALID_IP";
+    case OC_STACK_INVALID_PORT:
+        return "OC_STACK_INVALID_PORT";
+    case OC_STACK_INVALID_CALLBACK:
+        return "OC_STACK_INVALID_CALLBACK";
+    case OC_STACK_INVALID_METHOD:
+        return "OC_STACK_INVALID_METHOD";
+    case OC_STACK_NO_MEMORY:
+        return "OC_STACK_NO_MEMORY";
+    case OC_STACK_COMM_ERROR:
+        return "OC_STACK_COMM_ERROR";
+    case OC_STACK_INVALID_PARAM:
+        return "OC_STACK_INVALID_PARAM";
+    case OC_STACK_NOTIMPL:
+        return "OC_STACK_NOTIMPL";
+    case OC_STACK_NO_RESOURCE:
+        return "OC_STACK_NO_RESOURCE";
+    case OC_STACK_RESOURCE_ERROR:
+        return "OC_STACK_RESOURCE_ERROR";
+    case OC_STACK_SLOW_RESOURCE:
+        return "OC_STACK_SLOW_RESOURCE";
+    case OC_STACK_NO_OBSERVERS:
+        return "OC_STACK_NO_OBSERVERS";
+    case OC_STACK_ERROR:
+        return "OC_STACK_ERROR";
+    default:
+        return "UNKNOWN";
+    }
+}
+
index f711552..30f44d6 100644 (file)
@@ -13,14 +13,13 @@ linux_sample_env = lib_env.Clone()
 # Build flags
 ######################################################################
 linux_sample_env.AppendUnique(CPPPATH = ['include'])
-linux_sample_env.AppendUnique(CPPPATH = ['../../../SSMCore/include'])
-linux_sample_env.AppendUnique(CPPPATH = ['../../../SSMCore/src'])
-linux_sample_env.AppendUnique(CPPPATH = ['../../../SDK/include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../SDK/cpp/include'])
 linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 linux_sample_env.AppendUnique(LIBS = ['libSSMSDK'])
-linux_sample_env.AppendUnique(LIBS = ['libSSMCORE'])
+#linux_sample_env.AppendUnique(LIBS = ['libSSMCORE'])
+linux_sample_env.AppendUnique(LIBS = ['libSSMCore'])
 linux_sample_env.AppendUnique(LIBS = ['oc'])
 linux_sample_env.AppendUnique(LIBS = ['octbstack'])
 linux_sample_env.AppendUnique(LIBS = ['libcoap'])
@@ -32,5 +31,5 @@ linux_sample_env.AppendUnique(LIBS = ['pthread'])
 #build sampleapp
 ######################################################################
 ssmtesterapp = linux_sample_env.Program('SSMTesterApp', 'src/SSMTestApp.cpp')
-Alias("SSMTesterApp", ssmtesterapp)
+Alias("ssmtesterapp_sample", ssmtesterapp)
 env.AppendTarget('SSMTesterApp')
index 54a71c8..abf7cf7 100644 (file)
@@ -11,7 +11,7 @@ TARGET=SSMTesterApp
 
 CXX=g++
 CXX_FLAGS=-std=c++0x -Wall -DLINUX
-CXX_INC=-I${SRC_PATH}/ -I${INC_PATH}/ -I${OUTPUTS_DIR} -I${IOT_BASE}/include/ -I${IOT_LOG_DIR}/include/ -I${IOT_BASE}/csdk/stack/include -I${IOT_BASE}/csdk/ocsocket/include -I${IOT_BASE}/csdk/ocrandom/include -I${IOT_BASE}/csdk/logger/include -I${BOOST}
+CXX_INC=-I${SRC_PATH}/ -I${INC_PATH}/ -I${OUTPUTS_DIR} -I${BOOST}
 
 
 CXX_LIB+=${OUTPUTS_DIR}/${SSM_LIB} 
index c69bfd4..c68304d 100644 (file)
 
 #include <string>
 
-#include "OCResource.h"
-#include "OCPlatform.h"
 #include "SSMInterface.h"
-#include "SSMClient.h"
-#include "ISSMClientListener.h"
+
+using namespace OIC;
 
 namespace APPMenu
 {
@@ -47,11 +45,9 @@ typedef enum
     ALL_DISCOMPORT = 2, HALF_DISCOMPORT, LITTLE_DISCOMPORT, ALL_COMPORT
 } DIResult;
 
-class SSMTestApp: public ISSMClientListener
-    , public IQueryEngineEvent
+class SSMTestApp: public IQueryEngineEvent
 {
     private:
-        //SSMClient m_SSMClient;
         SSMInterface m_SSMClient;
 
     public:
@@ -63,7 +59,6 @@ class SSMTestApp: public ISSMClientListener
         void unregisterQuery();
 
         /* operations from listener interface */
-        void onRegisterQuery(const std::string &jsonData, SSMReturn &eCode);
         SSMRESULT onQueryEngineEvent(int cqid, IDataReader *pResult);
 };
 
index 4a017ba..50ba8fc 100644 (file)
@@ -24,6 +24,8 @@
 
 #include "SSMTestApp.h"
 
+using namespace std;
+
 SSMTestApp::SSMTestApp()
 {
 }
@@ -84,18 +86,6 @@ void SSMTestApp::unregisterQuery(void)
 }
 
 /* APP. Level Callback Function for Observer of client. */
-void SSMTestApp::onRegisterQuery(const std::string &jsonData, SSMReturn &eCode)
-{
-    if (eCode == SSM_SUCCESS)
-    {
-        std::cout << jsonData << std::endl;
-    }
-    else
-    {
-        std::cout << "Response error: " << eCode << std::endl;
-    }
-}
-
 SSMRESULT SSMTestApp::onQueryEngineEvent(int cqid, IDataReader *pResult)
 {
     int     dataCount = 0;
index d8b5dc8..712a83b 100644 (file)
@@ -60,7 +60,7 @@ class TemphumidResource
     public:
         /// Constructor
         TemphumidResource() :
-            m_humid(0), m_temp(0)
+            m_humid(0), m_temp(0), m_resourceHandle(0)
         {
             m_resourceUri = "/Thing_TempHumSensor";
             m_resourceTypes.push_back(COAP_TYPE_NAME);
index 39e0fff..73f43e7 100644 (file)
@@ -203,11 +203,15 @@ int main()
     {
         OC::OCPlatform::Configure(cfg);
 
+        OC::OCPlatform::startPresence(60);
+
         g_myResource.registerResource();
 
         int input = 0;
         cout << "Type any key to terminate" << endl;
         cin >> input;
+
+        OC::OCPlatform::stopPresence();
     }
     catch (std::exception e)
     {
index f6c65fa..a238dc0 100644 (file)
@@ -25,6 +25,6 @@ linux_sample_env.AppendUnique(LIBS = ['pthread'])
 ######################################################################
 #build sampleapp
 ######################################################################
-thsensorapp1 = linux_sample_env.Program('THSensorApp', 'src/ThingResourceServer1.cpp')
+thsensorapp1 = linux_sample_env.Program('THSensorApp1', 'src/ThingResourceServer1.cpp')
 Alias("thsensorapp1_sample", thsensorapp1)
 env.AppendTarget('thsensorapp1_sample')
index b32b589..c854f69 100644 (file)
@@ -60,7 +60,7 @@ class TemphumidResource
     public:
         /// Constructor
         TemphumidResource() :
-            m_humid(0), m_temp(0)
+            m_humid(0), m_temp(0), m_resourceHandle(0)
         {
             m_resourceUri = "/Thing_TempHumSensor1";
             m_resourceTypes.push_back(COAP_TYPE_NAME);
index c52416b..93c8e0d 100644 (file)
@@ -203,11 +203,15 @@ int main()
     {
         OC::OCPlatform::Configure(cfg);
 
+        OC::OCPlatform::startPresence(60);
+
         g_myResource.registerResource();
 
         int input = 0;
         cout << "Type any key to terminate" << endl;
         cin >> input;
+
+        OC::OCPlatform::stopPresence();
     }
     catch (std::exception e)
     {
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/SoftSensorDescription.xml b/service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/SoftSensorDescription.xml
deleted file mode 100644 (file)
index 7910214..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-<softsensors>
-       
-  <softsensor>
-    <name>DiscomfortIndexSensor</name>
-    <attributes>
-      <attribute>
-        <name>version</name>
-        <type>string</type>
-        <value>1.0</value>
-      </attribute>
-      <attribute>
-        <name>lifetime</name>
-        <type>int</type>
-        <value>60</value>
-      </attribute>
-    </attributes>
-    <outputs>
-      <output>
-        <name>timestamp</name>
-        <type>string</type>
-      </output>
-      <output>
-        <name>temperature</name>
-        <type>string</type>
-      </output>
-      <output>
-        <name>humidity</name>
-        <type>string</type>
-      </output>
-      <output>
-        <name>discomfortIndex</name>
-        <type>int</type>
-      </output>
-    </outputs>
-    <inputs>
-      <input>Thing_TempHumSensor</input>
-      <input>Thing_TempHumSensor1</input>
-    </inputs>
-  </softsensor>
-  
-</softsensors>
index 4aae123..d87e604 100644 (file)
@@ -38,7 +38,7 @@ ${TARGET}: ${OBJLIST}
 post_job:
        @echo " " 
        cp -Rdp ./${RST_NAME}/lib${TARGET}.so ${OUTPUTS_DIR}/
-       cp -Rdp ../../${SSXML_NAME} ${OUTPUTS_DIR}/
+       cp -Rdp ../../../${SSXML_NAME} ${OUTPUTS_DIR}/
        @echo "-------------- ${TARGET} Build Successful. -------------"
        @echo "Enter to ${RST_NAME} folder."
        @echo " " 
diff --git a/service/soft-sensor-manager/SoftSensorPlugin/SoftSensorDescription.xml b/service/soft-sensor-manager/SoftSensorPlugin/SoftSensorDescription.xml
new file mode 100644 (file)
index 0000000..bdf8018
--- /dev/null
@@ -0,0 +1,98 @@
+<softsensors>
+       
+  <softsensor>
+    <name>DiscomfortIndexSensor</name>
+    <attributes>
+      <attribute>
+        <name>version</name>
+        <type>string</type>
+        <value>1.0</value>
+      </attribute>
+      <attribute>
+        <name>lifetime</name>
+        <type>int</type>
+        <value>60</value>
+      </attribute>
+    </attributes>
+    <outputs>
+      <output>
+        <name>timestamp</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>temperature</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>humidity</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>discomfortIndex</name>
+        <type>int</type>
+      </output>
+    </outputs>
+    <inputs>
+      <input>Thing_TempHumSensor</input>
+      <input>Thing_TempHumSensor1</input>
+    </inputs>
+  </softsensor>
+  
+  <softsensor>
+    <name>IndoorTrajectorySensor</name>
+    <attributes>
+      <attribute>
+        <name>version</name>
+        <type>string</type>
+        <value>1.0</value>
+      </attribute>
+      <attribute>
+        <name>lifetime</name>
+        <type>int</type>
+        <value>60</value>
+      </attribute>
+    </attributes>
+    <outputs>
+      <output>
+        <name>trackeeID</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>timeT0</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>ref01T0</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>ref02T0</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>ref03T0</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>timeT1</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>ref01T1</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>ref02T1</name>
+        <type>string</type>
+      </output>
+      <output>
+        <name>ref03T1</name>
+        <type>string</type>
+      </output>
+    </outputs>
+    <inputs>
+      <input>Tracker_Thing</input>
+    </inputs>
+  </softsensor>
+  
+</softsensors>
index e0b44b8..e318153 100644 (file)
@@ -1,6 +1,2 @@
 ARDUINO_DIR = /usr/share/arduino
-#ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
-CC=avr-g++
-CCPLUS=avr-g++
-AR=avr-ar
-RANLIB=avr-ranlib
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
index d4def6d..500f7d1 100644 (file)
@@ -9,11 +9,11 @@ IOT_CSDK_RELEASE=${IOT_BASE}/csdk/linux/release
 IOT_LOG_DIR=${IOT_BASE}/oc_logger
 IOT_LIB=liboc.a
 IOT_CSDK_LIB=liboctbstack.a
-IOT_LOG_LIB=liboc_logger.a
+IOT_LOG_LIB=oc_logger.a
 
 # service folder path.
 FD_SSM=${ROOT_DIR}/service/soft-sensor-manager
-FD_SDK=${FD_SSM}/SDK
+FD_SDK=${FD_SSM}/SDK/cpp
 FD_SSMCORE=${FD_SSM}/SSMCore
 FD_SAMPLEAPP=${FD_SSM}/SampleApp
 FD_SOFTSENSOR=${FD_SSM}/SoftSensorPlugin
@@ -23,7 +23,7 @@ FD_BUILD=${FD_SSM}/build
 OUTPUTS_DIR=${FD_BUILD}/linux/release
 EXEC_DIR=${OUTPUTS_DIR}
 SSXML_NAME="SoftSensorDescription.xml"
-SSM_LIB = libSSM.a
+SSM_LIB = libSSMSDK.a
 SSMCORE_LIB=libSSMCore.a
 
 # SoftSensorManager makefile path
diff --git a/service/soft-sensor-manager/doc/SSM Developer s guide_v0.1.pdf b/service/soft-sensor-manager/doc/SSM Developer s guide_v0.1.pdf
deleted file mode 100644 (file)
index ce75a27..0000000
Binary files a/service/soft-sensor-manager/doc/SSM Developer s guide_v0.1.pdf and /dev/null differ
diff --git a/service/soft-sensor-manager/doc/SSM Getting Started_v0.1.pdf b/service/soft-sensor-manager/doc/SSM Getting Started_v0.1.pdf
deleted file mode 100644 (file)
index 3968a2f..0000000
Binary files a/service/soft-sensor-manager/doc/SSM Getting Started_v0.1.pdf and /dev/null differ
index 1fb3198..470b15f 100644 (file)
@@ -13,8 +13,7 @@ target_os = env.get('TARGET_OS')
 ######################################################################
 # Build flags
 ######################################################################
-things_manager_env.AppendUnique(CPPPATH = ['tgm/inc'])
-things_manager_env.AppendUnique(CPPPATH = ['sdk/inc'])
+things_manager_env.AppendUnique(CPPPATH = ['sdk/inc', 'sdk/src'])
 
 if target_os not in ['windows', 'winrt']:
        things_manager_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
@@ -28,9 +27,10 @@ if target_os == 'android':
 ######################################################################
 # Source files and Targets
 ######################################################################
-tgmsdk = things_manager_env.StaticLibrary('TGMSDKLibrary', 'sdk/src/TGMClient.cpp')
+tgm_src = env.Glob('sdk/src/*.cpp')
+tgmsdk = things_manager_env.StaticLibrary('TGMSDKLibrary', tgm_src)
 
 things_manager_env.InstallTarget(tgmsdk, 'libTGMSDK')
 
 #Go to build sample apps
-SConscript('sampleapp/SConscript')
\ No newline at end of file
+SConscript('sampleapp/SConscript')
diff --git a/service/things-manager/build/linux/Makefile b/service/things-manager/build/linux/Makefile
deleted file mode 100644 (file)
index 58009ec..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-.PHONY : pre resource sdk sampleapp
-
-#.PHONY : lib tgm sdk sampleapp 
-all: .PHONY
-
-pre:
-       -mkdir release
-
-resource:
-       cd ../../../../resource && $(MAKE)
-
-
-sdk:
-       cd ../../sdk/build/linux && $(MAKE)
-       cp -Rdp ../../sdk/build/linux/*.a release/
-
-
-sampleapp:
-       cd ../../sampleapp/linux/tgmclient && $(MAKE)
-       cp -Rdp ../../sampleapp/linux/tgmclient/tgmclient release/
-
-clean:
-       cd ../../sdk/build/linux && $(MAKE) clean
-       cd ../../sampleapp/linux/tgmclient && $(MAKE) clean
-
-       rm -rf ./release/*
diff --git a/service/things-manager/build/linux/makefile b/service/things-manager/build/linux/makefile
new file mode 100644 (file)
index 0000000..4fc7d7e
--- /dev/null
@@ -0,0 +1,32 @@
+.PHONY : pre resource sdk sampleapp
+#.PHONY : lib tgm sdk sampleapp
+all: .PHONY
+
+pre:
+       -mkdir release
+
+resource:
+       cd ../../../../resource && $(MAKE)
+
+
+sdk:
+       cd ../../sdk/build/linux && $(MAKE)
+       cp -Rdp ../../sdk/build/linux/*.a release/
+
+sampleapp:
+       cd ../../sampleapp/linux && $(MAKE)
+       cp -Rdp ../../sampleapp/linux/configuration/con-server release/
+       cp -Rdp ../../sampleapp/linux/configuration/con-client release/
+       cp -Rdp ../../sampleapp/linux/configuration/bootstrapserver release/
+       cp -Rdp ../../sampleapp/linux/groupaction/groupserver release/
+       cp -Rdp ../../sampleapp/linux/groupaction/bookmark release/
+       cp -Rdp ../../sampleapp/linux/groupaction/lightserver release/
+       cp -Rdp ../../sampleapp/linux/groupsyncaction/group release/
+       cp -Rdp ../../sampleapp/linux/groupsyncaction/musicplayer release/
+       cp -Rdp ../../sampleapp/linux/groupsyncaction/phone release/
+       cp -Rdp ../../sampleapp/linux/groupsyncaction/speaker release/
+
+clean:
+       cd ../../sdk/build/linux && $(MAKE) clean
+       cd ../../sampleapp/linux && $(MAKE) clean
+       rm -rf ./release
index bd1b631..7fe88ad 100644 (file)
@@ -4,6 +4,21 @@
 
 Import('env')
 
-if env.get('TARGET_OS') == 'linux':
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+sample_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+
+######################################################################
+# Source files and Targets
+######################################################################
+if target_os == 'linux' :
        # Build linux sample app
-       SConscript('linux/tgmclient/SConscript')
+       SConscript('linux/configuration/SConscript')
+       SConscript('linux/groupaction/SConscript')
+       SConscript('linux/groupsyncaction/SConscript')
diff --git a/service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.cpp b/service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.cpp
new file mode 100644 (file)
index 0000000..7ee28d1
--- /dev/null
@@ -0,0 +1,591 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+#include "ConfigurationCollection.h"
+
+using namespace OC;
+
+/// This function internally calls registerResource API.
+void ConfigurationCollection::createResources(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (callback == NULL)
+    {
+        std::cout << "callback should be binded\t";
+        return;
+    }
+
+    // This will internally create and register the resource.
+    OCStackResult result = registerResource(m_configurationHandle, m_configurationUri,
+            m_configurationTypes[0], m_configurationInterfaces[0], callback,
+            OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (configuration) was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_configurationHandle, m_configurationInterfaces[1]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_configurationHandle, m_configurationInterfaces[2]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = registerResource(m_regionHandle, m_regionUri, m_regionTypes[0], m_regionInterfaces[0],
+            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (region) was unsuccessful\n";
+    }
+
+    result = registerResource(m_timeHandle, m_timeUri, m_timeTypes[0], m_timeInterfaces[0],
+            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (time) was unsuccessful\n";
+    }
+
+    result = registerResource(m_networkHandle, m_networkUri, m_networkTypes[0],
+            m_networkInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (network) was unsuccessful\n";
+    }
+
+    result = registerResource(m_securityHandle, m_securityUri, m_securityTypes[0],
+            m_securityInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (security) was unsuccessful\n";
+    }
+
+    result = bindResource(m_configurationHandle, m_regionHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding region resource to room was unsuccessful\n";
+    }
+
+    result = bindResource(m_configurationHandle, m_timeHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding time resource to room was unsuccessful\n";
+    }
+
+    result = bindResource(m_configurationHandle, m_networkHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding network resource to room was unsuccessful\n";
+    }
+
+    result = bindResource(m_configurationHandle, m_securityHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding security resource to room was unsuccessful\n";
+    }
+
+    std::cout << "Configuration Collection is Created!(URI: " << m_configurationUri << ") \n";
+
+    myTimeCollection->createResources(callback);
+    myNetworkCollection->createResources(callback);
+    mySecurityCollection->createResources(callback);
+
+}
+
+void ConfigurationCollection::setConfigurationRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_configurationValue = value;
+
+        std::cout << "\t\t\t\t" << "m_configurationValue: " << m_configurationValue << std::endl;
+    }
+}
+
+void ConfigurationCollection::setTimeRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("link", value))
+    {
+        // NOT ALLOWED
+
+        std::cout << "\t\t\t\t" << "link: " << m_timeLink << std::endl;
+    }
+}
+
+void ConfigurationCollection::setNetworkRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("link", value))
+    {
+        // NOT ALLOWED
+
+        std::cout << "\t\t\t\t" << "link: " << m_networkLink << std::endl;
+    }
+}
+
+void ConfigurationCollection::setSecurityRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("link", value))
+    {
+        // NOT ALLOWED
+
+        std::cout << "\t\t\t\t" << "link: " << m_securityLink << std::endl;
+    }
+}
+
+void ConfigurationCollection::setRegionRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_regionValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_regionValue << std::endl;
+    }
+}
+
+OCRepresentation ConfigurationCollection::getTimeRepresentation()
+{
+    m_timeRep.setValue("link", m_timeLink);
+
+    return m_timeRep;
+}
+
+OCRepresentation ConfigurationCollection::getNetworkRepresentation()
+{
+    m_networkRep.setValue("link", m_networkLink);
+
+    return m_networkRep;
+}
+
+OCRepresentation ConfigurationCollection::getSecurityRepresentation()
+{
+    m_securityRep.setValue("link", m_securityLink);
+
+    return m_securityRep;
+}
+
+OCRepresentation ConfigurationCollection::getRegionRepresentation()
+{
+    m_regionRep.setValue("value", m_regionValue);
+
+    return m_regionRep;
+}
+
+OCRepresentation ConfigurationCollection::getConfigurationRepresentation()
+{
+    m_configurationRep.clearChildren();
+
+    m_configurationRep.addChild(getRegionRepresentation());
+    m_configurationRep.addChild(getTimeRepresentation());
+    m_configurationRep.addChild(getNetworkRepresentation());
+    m_configurationRep.addChild(getSecurityRepresentation());
+
+    m_configurationRep.setValue("value", m_configurationValue);
+
+    return m_configurationRep;
+}
+
+std::string ConfigurationCollection::getConfigurationUri()
+{
+    return m_configurationUri;
+}
+
+std::string ConfigurationCollection::getTimeUri()
+{
+    return m_timeUri;
+}
+
+std::string ConfigurationCollection::getNetworkUri()
+{
+    return m_networkUri;
+}
+
+std::string ConfigurationCollection::getSecurityUri()
+{
+    return m_securityUri;
+}
+
+std::string ConfigurationCollection::getRegionUri()
+{
+    return m_regionUri;
+}
+
+void ConfigurationCollection::factoryReset()
+{
+    m_configurationValue = defaultConfigurationValue;
+    m_regionValue = defaultRegionValue;
+    m_timeLink = defaultTimeLink;
+    m_networkLink = defaultNetworkLink;
+    m_securityLink = defaultSecurityLink;
+
+    myTimeCollection->factoryReset();
+    myNetworkCollection->factoryReset();
+    mySecurityCollection->factoryReset();
+}
+
+/// This function internally calls registerResource API.
+void TimeCollection::createResources(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (callback == NULL)
+    {
+        std::cout << "callback should be binded\t";
+        return;
+    }
+
+    // This will internally create and register the resource.
+    OCStackResult result = registerResource(m_timeHandle, m_timeUri, m_timeTypes[0],
+            m_timeInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (time) was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_timeHandle, m_timeInterfaces[1]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_timeHandle, m_timeInterfaces[2]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = registerResource(m_currentTimeHandle, m_currentTimeUri, m_currentTimeTypes[0],
+            m_currentTimeInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (currentTime) was unsuccessful\n";
+    }
+
+    result = bindResource(m_timeHandle, m_currentTimeHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding currentTime resource to room was unsuccessful\n";
+    }
+
+    std::cout << "Time Collection is Created!(URI: " << m_timeUri << ") \n";
+}
+
+void TimeCollection::setTimeRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_timeValue = value;
+
+        std::cout << "\t\t\t\t" << "m_timeValue: " << m_timeValue << std::endl;
+    }
+}
+
+void TimeCollection::setCurrentTimeRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("currentTime", value))
+    {
+        m_currentTimeValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_currentTimeValue << std::endl;
+    }
+}
+
+OCRepresentation TimeCollection::getCurrentTimeRepresentation()
+{
+    m_currentTimeRep.setValue("value", m_currentTimeValue);
+
+    return m_currentTimeRep;
+}
+
+OCRepresentation TimeCollection::getTimeRepresentation()
+{
+    m_timeRep.clearChildren();
+
+    m_timeRep.addChild(getCurrentTimeRepresentation());
+
+    m_timeRep.setValue("value", m_timeValue);
+
+    return m_timeRep;
+}
+
+std::string TimeCollection::getTimeUri()
+{
+    return m_timeUri;
+}
+
+std::string TimeCollection::getCurrentTimeUri()
+{
+    return m_currentTimeUri;
+}
+
+void TimeCollection::factoryReset()
+{
+    m_timeValue = defaultTimeValue;
+    m_currentTimeValue = defaultCurrentTimeValue;
+}
+
+/// This function internally calls registerResource API.
+void NetworkCollection::createResources(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (callback == NULL)
+    {
+        std::cout << "callback should be binded\t";
+        return;
+    }
+
+    // This will internally create and register the resource.
+    OCStackResult result = registerResource(m_networkHandle, m_networkUri, m_networkTypes[0],
+            m_networkInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (network) was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_networkHandle, m_networkInterfaces[1]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_networkHandle, m_networkInterfaces[2]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = registerResource(m_IPAddressHandle, m_IPAddressUri, m_IPAddressTypes[0],
+            m_IPAddressInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (IPAddress) was unsuccessful\n";
+    }
+
+    result = bindResource(m_networkHandle, m_IPAddressHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding IPAddress resource to room was unsuccessful\n";
+    }
+
+    std::cout << "Network Collection is Created!(URI: " << m_networkUri << ") \n";
+}
+
+void NetworkCollection::setNetworkRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_networkValue = value;
+
+        std::cout << "\t\t\t\t" << "m_networkValue: " << m_networkValue << std::endl;
+    }
+}
+
+void NetworkCollection::setIPAddressRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("IPAddress", value))
+    {
+        m_IPAddressValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_IPAddressValue << std::endl;
+    }
+}
+OCRepresentation NetworkCollection::getIPAddressRepresentation()
+{
+    m_IPAddressRep.setValue("value", m_IPAddressValue);
+
+    return m_IPAddressRep;
+}
+
+OCRepresentation NetworkCollection::getNetworkRepresentation()
+{
+    m_networkRep.clearChildren();
+
+    m_networkRep.addChild(getIPAddressRepresentation());
+
+    m_networkRep.setValue("value", m_networkValue);
+
+    return m_networkRep;
+}
+
+std::string NetworkCollection::getNetworkUri()
+{
+    return m_networkUri;
+}
+
+std::string NetworkCollection::getIPAddressUri()
+{
+    return m_IPAddressUri;
+}
+
+void NetworkCollection::factoryReset()
+{
+    m_networkValue = defaultNetworkValue;
+    m_IPAddressValue = defaultIPAddressValue;
+}
+
+/// This function internally calls registerResource API.
+void SecurityCollection::createResources(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (callback == NULL)
+    {
+        std::cout << "callback should be binded\t";
+        return;
+    }
+
+    // This will internally create and register the resource.
+    OCStackResult result = registerResource(m_securityHandle, m_securityUri, m_securityTypes[0],
+            m_securityInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (security) was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_securityHandle, m_securityInterfaces[1]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_securityHandle, m_securityInterfaces[2]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = registerResource(m_modeHandle, m_modeUri, m_modeTypes[0], m_modeInterfaces[0],
+            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (mode) was unsuccessful\n";
+    }
+
+    result = bindResource(m_securityHandle, m_modeHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding mode resource to room was unsuccessful\n";
+    }
+
+    std::cout << "Security Collection is Created!(URI: " << m_securityUri << ") \n";
+}
+
+void SecurityCollection::setSecurityRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_securityValue = value;
+
+        std::cout << "\t\t\t\t" << "m_securityValue: " << m_securityValue << std::endl;
+    }
+}
+
+void SecurityCollection::setModeRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("mode", value))
+    {
+        m_modeValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_modeValue << std::endl;
+    }
+}
+
+OCRepresentation SecurityCollection::getModeRepresentation()
+{
+    m_modeRep.setValue("value", m_modeValue);
+
+    return m_modeRep;
+}
+
+OCRepresentation SecurityCollection::getSecurityRepresentation()
+{
+    m_securityRep.clearChildren();
+
+    m_securityRep.addChild(getModeRepresentation());
+
+    m_securityRep.setValue("value", m_securityValue);
+
+    return m_securityRep;
+}
+
+std::string SecurityCollection::getSecurityUri()
+{
+    return m_securityUri;
+}
+
+std::string SecurityCollection::getModeUri()
+{
+    return m_modeUri;
+}
+
+void SecurityCollection::factoryReset()
+{
+    m_securityValue = defaultSecurityValue;
+    m_modeValue = defaultModeValue;
+}
+
diff --git a/service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.h b/service/things-manager/sampleapp/linux/configuration/ConfigurationCollection.h
new file mode 100644 (file)
index 0000000..cbc1db5
--- /dev/null
@@ -0,0 +1,535 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+
+static std::string defaultURIPrefix = "/oic/con";
+static std::string defaultResourceTypePrefix = "oic.con";
+
+extern std::string defaultTimeValue;
+extern std::string defaultCurrentTimeValue;
+
+class TimeCollection
+{
+public:
+
+    // diagnostics members
+    std::string m_timeUri;
+    std::string m_timeValue;
+    std::vector< std::string > m_timeTypes;
+    std::vector< std::string > m_timeInterfaces;
+    OCResourceHandle m_timeHandle;
+    OCRepresentation m_timeRep;
+
+    // factory reset members
+    std::string m_currentTimeUri;
+    std::string m_currentTimeValue;
+    std::vector< std::string > m_currentTimeTypes;
+    std::vector< std::string > m_currentTimeInterfaces;
+    OCResourceHandle m_currentTimeHandle;
+    OCRepresentation m_currentTimeRep;
+
+public:
+    /// Constructor
+    TimeCollection() :
+            m_timeValue(defaultTimeValue), m_currentTimeValue(defaultCurrentTimeValue)
+    {
+        m_currentTimeUri = defaultURIPrefix + "/time/0/currentTime"; // URI of the resource
+        m_currentTimeTypes.push_back("oic.con.time.currentTime"); // resource type name.
+        m_currentTimeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_currentTimeRep.setUri(m_currentTimeUri);
+        m_currentTimeRep.setResourceTypes(m_currentTimeTypes);
+        m_currentTimeRep.setResourceInterfaces(m_currentTimeInterfaces);
+        m_currentTimeRep.setValue("value", m_currentTimeValue);
+        m_currentTimeHandle = NULL;
+
+        m_timeUri = defaultURIPrefix + "/time"; // URI of the resource
+        m_timeTypes.push_back("oic.con.time"); // resource type name.
+        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_timeInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_timeInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_timeRep.setValue("value", m_timeValue);
+        m_timeRep.setUri(m_timeUri);
+        m_timeRep.setResourceTypes(m_timeTypes);
+        m_timeRep.setResourceInterfaces(m_timeInterfaces);
+        m_timeHandle = NULL;
+    }
+    ;
+
+    /// Constructor
+    TimeCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
+            m_timeValue(defaultTimeValue), m_currentTimeValue(defaultCurrentTimeValue)
+    {
+        m_currentTimeUri = URIPrefix + "/time/0/currentTime"; // URI of the resource
+        m_currentTimeTypes.push_back(ResourceTypePrefix + ".time.currentTime"); // type name.
+        m_currentTimeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_currentTimeRep.setUri(m_currentTimeUri);
+        m_currentTimeRep.setResourceTypes(m_currentTimeTypes);
+        m_currentTimeRep.setResourceInterfaces(m_currentTimeInterfaces);
+        m_currentTimeRep.setValue("value", m_currentTimeValue);
+        m_currentTimeHandle = NULL;
+
+        m_timeUri = URIPrefix + "/time"; // URI of the resource
+        m_timeTypes.push_back(ResourceTypePrefix + ".time"); // resource type name.
+        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_timeInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_timeInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_timeRep.setValue("value", m_timeValue);
+        m_timeRep.setUri(m_timeUri);
+        m_timeRep.setResourceTypes(m_timeTypes);
+        m_timeRep.setResourceInterfaces(m_timeInterfaces);
+        m_timeHandle = NULL;
+    }
+    ;
+
+    /// This function internally calls registerResource API.
+    void createResources(ResourceEntityHandler callback);
+
+    void setTimeRepresentation(OCRepresentation& rep);
+    void setCurrentTimeRepresentation(OCRepresentation& rep);
+
+    OCRepresentation getTimeRepresentation();
+    OCRepresentation getCurrentTimeRepresentation();
+
+    std::string getTimeUri();
+    std::string getCurrentTimeUri();
+
+    void factoryReset();
+
+};
+
+extern std::string defaultNetworkValue;
+extern std::string defaultIPAddressValue;
+
+class NetworkCollection
+{
+public:
+
+    // diagnostics members
+    std::string m_networkUri;
+    std::string m_networkValue;
+    std::vector< std::string > m_networkTypes;
+    std::vector< std::string > m_networkInterfaces;
+    OCResourceHandle m_networkHandle;
+    OCRepresentation m_networkRep;
+
+    // factory reset members
+    std::string m_IPAddressUri;
+    std::string m_IPAddressValue;
+    std::vector< std::string > m_IPAddressTypes;
+    std::vector< std::string > m_IPAddressInterfaces;
+    OCResourceHandle m_IPAddressHandle;
+    OCRepresentation m_IPAddressRep;
+
+public:
+
+    /// Constructor
+    NetworkCollection() :
+            m_networkValue(defaultNetworkValue), m_IPAddressValue(defaultIPAddressValue)
+    {
+        m_IPAddressUri = defaultURIPrefix + "/network/0/IPAddress"; // URI of the resource
+        m_IPAddressTypes.push_back("oic.con.network.IPAddress"); // resource type name.
+        m_IPAddressInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_IPAddressRep.setUri(m_IPAddressUri);
+        m_IPAddressRep.setResourceTypes(m_IPAddressTypes);
+        m_IPAddressRep.setResourceInterfaces(m_IPAddressInterfaces);
+        m_IPAddressRep.setValue("value", m_IPAddressValue);
+        m_IPAddressHandle = NULL;
+
+        m_networkUri = defaultURIPrefix + "/network"; // URI of the resource
+        m_networkTypes.push_back("oic.con.network"); // resource type name.
+        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_networkInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_networkInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_networkRep.setValue("value", m_networkValue);
+        m_networkRep.setUri(m_networkUri);
+        m_networkRep.setResourceTypes(m_networkTypes);
+        m_networkRep.setResourceInterfaces(m_networkInterfaces);
+        m_networkHandle = NULL;
+    }
+    ;
+
+    /// Constructor
+    NetworkCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
+            m_networkValue(defaultNetworkValue), m_IPAddressValue(defaultIPAddressValue)
+    {
+        m_IPAddressUri = URIPrefix + "/network/0/IPAddress"; // URI of the resource
+        m_IPAddressTypes.push_back(ResourceTypePrefix + "network.IPAddress"); // resource type name.
+        m_IPAddressInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_IPAddressRep.setUri(m_IPAddressUri);
+        m_IPAddressRep.setResourceTypes(m_IPAddressTypes);
+        m_IPAddressRep.setResourceInterfaces(m_IPAddressInterfaces);
+        m_IPAddressRep.setValue("value", m_IPAddressValue);
+        m_IPAddressHandle = NULL;
+
+        m_networkUri = URIPrefix + "/network"; // URI of the resource
+        m_networkTypes.push_back(ResourceTypePrefix + ".network"); // resource type name.
+        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_networkInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_networkInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_networkRep.setValue("value", m_networkValue);
+        m_networkRep.setUri(m_networkUri);
+        m_networkRep.setResourceTypes(m_networkTypes);
+        m_networkRep.setResourceInterfaces(m_networkInterfaces);
+        m_networkHandle = NULL;
+    }
+    ;
+
+    /// This function internally calls registerResource API.
+    void createResources(ResourceEntityHandler callback);
+
+    void setNetworkRepresentation(OCRepresentation& rep);
+    void setIPAddressRepresentation(OCRepresentation& rep);
+
+    OCRepresentation getNetworkRepresentation();
+    OCRepresentation getIPAddressRepresentation();
+
+    std::string getNetworkUri();
+    std::string getIPAddressUri();
+
+    void factoryReset();
+
+};
+
+extern std::string defaultSecurityValue;
+extern std::string defaultModeValue;
+
+class SecurityCollection
+{
+public:
+
+    // diagnostics members
+    std::string m_securityUri;
+    std::string m_securityValue;
+    std::vector< std::string > m_securityTypes;
+    std::vector< std::string > m_securityInterfaces;
+    OCResourceHandle m_securityHandle;
+    OCRepresentation m_securityRep;
+
+    // factory reset members
+    std::string m_modeUri;
+    std::string m_modeValue;
+    std::vector< std::string > m_modeTypes;
+    std::vector< std::string > m_modeInterfaces;
+    OCResourceHandle m_modeHandle;
+    OCRepresentation m_modeRep;
+
+public:
+    /// Constructor
+    SecurityCollection() :
+            m_securityValue(defaultSecurityValue), m_modeValue(defaultModeValue)
+    {
+        m_modeUri = defaultURIPrefix + "/security/0/mode"; // URI of the resource
+        m_modeTypes.push_back("oic.con.security.mode"); // resource type name.
+        m_modeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_modeRep.setUri(m_modeUri);
+        m_modeRep.setResourceTypes(m_modeTypes);
+        m_modeRep.setResourceInterfaces(m_modeInterfaces);
+        m_modeRep.setValue("value", m_modeValue);
+        m_modeHandle = NULL;
+
+        m_securityUri = defaultURIPrefix + "/security"; // URI of the resource
+        m_securityTypes.push_back("oic.con.security"); // resource type name.
+        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_securityInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_securityInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_securityRep.setValue("value", m_securityValue);
+        m_securityRep.setUri(m_securityUri);
+        m_securityRep.setResourceTypes(m_securityTypes);
+        m_securityRep.setResourceInterfaces(m_securityInterfaces);
+        m_securityHandle = NULL;
+    }
+    ;
+
+    /// Constructor
+    SecurityCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
+            m_securityValue(defaultSecurityValue), m_modeValue(defaultModeValue)
+    {
+        m_modeUri = URIPrefix + "/security/0/mode"; // URI of the resource
+        m_modeTypes.push_back(ResourceTypePrefix + ".security.mode"); // resource type name.
+        m_modeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_modeRep.setUri(m_modeUri);
+        m_modeRep.setResourceTypes(m_modeTypes);
+        m_modeRep.setResourceInterfaces(m_modeInterfaces);
+        m_modeRep.setValue("value", m_modeValue);
+        m_modeHandle = NULL;
+
+        m_securityUri = URIPrefix + "/security"; // URI of the resource
+        m_securityTypes.push_back(ResourceTypePrefix + ".security"); // resource type name.
+        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_securityInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_securityInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_securityRep.setValue("value", m_securityValue);
+        m_securityRep.setUri(m_securityUri);
+        m_securityRep.setResourceTypes(m_securityTypes);
+        m_securityRep.setResourceInterfaces(m_securityInterfaces);
+        m_securityHandle = NULL;
+    }
+    ;
+
+    /// This function internally calls registerResource API.
+    void createResources(ResourceEntityHandler callback);
+
+    void setSecurityRepresentation(OCRepresentation& rep);
+    void setModeRepresentation(OCRepresentation& rep);
+
+    OCRepresentation getSecurityRepresentation();
+    OCRepresentation getModeRepresentation();
+
+    std::string getSecurityUri();
+    std::string getModeUri();
+
+    void factoryReset();
+
+};
+
+extern std::string defaultConfigurationValue;
+extern std::string defaultRegionValue;
+static std::string defaultTimeLink = "/con/con/0/time";
+static std::string defaultNetworkLink = "/con/con/0/network";
+static std::string defaultSecurityLink = "/con/con/0/security";
+
+class ConfigurationCollection
+{
+public:
+    TimeCollection *myTimeCollection;
+    NetworkCollection *myNetworkCollection;
+    SecurityCollection *mySecurityCollection;
+
+public:
+    // Configuration members
+    std::string m_configurationUri;
+    std::string m_configurationValue;
+    std::vector< std::string > m_configurationTypes;
+    std::vector< std::string > m_configurationInterfaces;
+    OCResourceHandle m_configurationHandle;
+    OCRepresentation m_configurationRep;
+
+    // Security members
+    std::string m_regionUri;
+    std::string m_regionValue;
+    std::vector< std::string > m_regionTypes;
+    std::vector< std::string > m_regionInterfaces;
+    OCResourceHandle m_regionHandle;
+    OCRepresentation m_regionRep;
+
+    // Time members
+    std::string m_timeUri;
+    std::string m_timeLink;
+    std::vector< std::string > m_timeTypes;
+    std::vector< std::string > m_timeInterfaces;
+    OCResourceHandle m_timeHandle;
+    OCRepresentation m_timeRep;
+
+    // Network members
+    std::string m_networkUri;
+    std::string m_networkLink;
+    std::vector< std::string > m_networkTypes;
+    std::vector< std::string > m_networkInterfaces;
+    OCResourceHandle m_networkHandle;
+    OCRepresentation m_networkRep;
+
+    // Security members
+    std::string m_securityUri;
+    std::string m_securityLink;
+    std::vector< std::string > m_securityTypes;
+    std::vector< std::string > m_securityInterfaces;
+    OCResourceHandle m_securityHandle;
+    OCRepresentation m_securityRep;
+
+public:
+    /// Constructor
+    ConfigurationCollection() :
+            m_configurationValue(defaultConfigurationValue), m_regionValue(defaultRegionValue), m_timeLink(
+                    defaultTimeLink), m_networkLink(defaultNetworkLink), m_securityLink(
+                    defaultSecurityLink)
+    {
+        m_regionUri = defaultURIPrefix + "/0/region"; // URI of the resource
+        m_regionTypes.push_back(defaultResourceTypePrefix + ".region"); // resource type name.
+        m_regionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_regionRep.setUri(m_regionUri);
+        m_regionRep.setResourceTypes(m_regionTypes);
+        m_regionRep.setResourceInterfaces(m_regionInterfaces);
+        m_regionRep.setValue("value", m_regionValue);
+        m_regionHandle = NULL;
+
+        m_timeUri = defaultURIPrefix + "/0/time"; // URI of the resource
+        m_timeTypes.push_back(defaultResourceTypePrefix + ".time"); // resource type name.
+        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_timeRep.setUri(m_timeUri);
+        m_timeRep.setResourceTypes(m_timeTypes);
+        m_timeRep.setResourceInterfaces(m_timeInterfaces);
+        m_timeRep.setValue("link", m_timeLink);
+        m_timeHandle = NULL;
+
+        m_networkUri = defaultURIPrefix + "/0/net"; // URI of the resource
+        m_networkTypes.push_back(defaultResourceTypePrefix + ".net"); // resource type name.
+        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_networkRep.setUri(m_networkUri);
+        m_networkRep.setResourceTypes(m_networkTypes);
+        m_networkRep.setResourceInterfaces(m_networkInterfaces);
+        m_networkRep.setValue("link", m_networkLink);
+        m_networkHandle = NULL;
+
+        m_securityUri = defaultURIPrefix + "/0/sec"; // URI of the resource
+        m_securityTypes.push_back(defaultResourceTypePrefix + ".sec"); // resource type name.
+        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_securityRep.setUri(m_securityUri);
+        m_securityRep.setResourceTypes(m_securityTypes);
+        m_securityRep.setResourceInterfaces(m_securityInterfaces);
+        m_securityRep.setValue("link", m_securityLink);
+        m_securityHandle = NULL;
+
+        m_configurationUri = defaultURIPrefix + ""; // URI of the resource
+        m_configurationTypes.push_back(defaultResourceTypePrefix + ""); // resource type name.
+        m_configurationInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_configurationInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_configurationInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_configurationRep.setValue("value", m_configurationValue);
+        m_configurationRep.setUri(m_configurationUri);
+        m_configurationRep.setResourceTypes(m_configurationTypes);
+        m_configurationRep.setResourceInterfaces(m_configurationInterfaces);
+        m_configurationHandle = NULL;
+
+        myTimeCollection = new TimeCollection();
+        myNetworkCollection = new NetworkCollection();
+        mySecurityCollection = new SecurityCollection();
+    }
+    ;
+
+    /// Constructor
+    ConfigurationCollection(std::string URIPrefix, std::string ResourceTypePrefix) :
+            m_configurationValue(defaultConfigurationValue), m_regionValue(defaultRegionValue), m_timeLink(
+                    defaultTimeLink), m_networkLink(defaultNetworkLink), m_securityLink(
+                    defaultSecurityLink)
+    {
+        m_regionUri = URIPrefix + "/0/region"; // URI of the resource
+        m_regionTypes.push_back(ResourceTypePrefix + ".region"); // type name.
+        m_regionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_regionRep.setUri(m_regionUri);
+        m_regionRep.setResourceTypes(m_regionTypes);
+        m_regionRep.setResourceInterfaces(m_regionInterfaces);
+        m_regionRep.setValue("value", m_regionValue);
+        m_regionHandle = NULL;
+
+        m_timeUri = URIPrefix + "/0/time"; // URI of the resource
+        m_timeTypes.push_back(ResourceTypePrefix + ".time"); // resource type name.
+        m_timeInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_timeRep.setUri(m_timeUri);
+        m_timeRep.setResourceTypes(m_timeTypes);
+        m_timeRep.setResourceInterfaces(m_timeInterfaces);
+        m_timeRep.setValue("link", m_timeLink);
+        m_timeHandle = NULL;
+
+        m_networkUri = URIPrefix + "/0/net"; // URI of the resource
+        m_networkTypes.push_back(ResourceTypePrefix + ".net"); // resource type name.
+        m_networkInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_networkRep.setUri(m_networkUri);
+        m_networkRep.setResourceTypes(m_networkTypes);
+        m_networkRep.setResourceInterfaces(m_networkInterfaces);
+        m_networkRep.setValue("link", m_networkLink);
+        m_networkHandle = NULL;
+
+        m_securityUri = URIPrefix + "/0/sec"; // URI of the resource
+        m_securityTypes.push_back(ResourceTypePrefix + ".sec"); // resource type name.
+        m_securityInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_securityRep.setUri(m_securityUri);
+        m_securityRep.setResourceTypes(m_securityTypes);
+        m_securityRep.setResourceInterfaces(m_securityInterfaces);
+        m_securityRep.setValue("link", m_securityLink);
+        m_securityHandle = NULL;
+
+        m_configurationUri = URIPrefix + ""; // URI of the resource
+        m_configurationTypes.push_back(ResourceTypePrefix + ""); // resource type name.
+        m_configurationInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_configurationInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_configurationInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_configurationRep.setValue("value", m_configurationValue);
+        m_configurationRep.setUri(m_configurationUri);
+        m_configurationRep.setResourceTypes(m_configurationTypes);
+        m_configurationRep.setResourceInterfaces(m_configurationInterfaces);
+        m_configurationHandle = NULL;
+
+        myTimeCollection = new TimeCollection(URIPrefix, ResourceTypePrefix);
+        myNetworkCollection = new NetworkCollection(URIPrefix, ResourceTypePrefix);
+        mySecurityCollection = new SecurityCollection(URIPrefix, ResourceTypePrefix);
+    }
+    ;
+
+    ~ConfigurationCollection()
+    {
+        free(myTimeCollection);
+        free(myNetworkCollection);
+        free(mySecurityCollection);
+    }
+
+    /// This function internally calls registerResource API.
+    void createResources(ResourceEntityHandler callback);
+
+    void setConfigurationRepresentation(OCRepresentation& rep);
+    void setTimeRepresentation(OCRepresentation& rep);
+    void setNetworkRepresentation(OCRepresentation& rep);
+    void setSecurityRepresentation(OCRepresentation& rep);
+    void setRegionRepresentation(OCRepresentation& rep);
+
+    OCRepresentation getTimeRepresentation();
+    OCRepresentation getNetworkRepresentation();
+    OCRepresentation getSecurityRepresentation();
+    OCRepresentation getRegionRepresentation();
+    OCRepresentation getConfigurationRepresentation();
+
+    std::string getConfigurationUri();
+    std::string getTimeUri();
+    std::string getNetworkUri();
+    std::string getSecurityUri();
+    std::string getRegionUri();
+
+    void factoryReset();
+
+};
diff --git a/service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.cpp b/service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.cpp
new file mode 100644 (file)
index 0000000..31eaf1e
--- /dev/null
@@ -0,0 +1,245 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+#include "DiagnosticsCollection.h"
+
+using namespace OC;
+
+/// This function internally calls registerResource API.
+void DiagnosticsCollection::createResources(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (callback == NULL)
+    {
+        std::cout << "callback should be binded\t";
+        return;
+    }
+
+    // This will internally create and register the resource.
+    OCStackResult result = registerResource(m_diagnosticsHandle, m_diagnosticsUri,
+            m_diagnosticsTypes[0], m_diagnosticsInterfaces[0], callback,
+            OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (diagnostics) was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_diagnosticsHandle, m_diagnosticsInterfaces[1]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_diagnosticsHandle, m_diagnosticsInterfaces[2]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = registerResource(m_factoryResetHandle, m_factoryResetUri, m_factoryResetTypes[0],
+            m_factoryResetInterfaces[0], callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (factoryReset) was unsuccessful\n";
+    }
+
+    result = registerResource(m_rebootHandle, m_rebootUri, m_rebootTypes[0], m_rebootInterfaces[0],
+            callback, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (reboot) was unsuccessful\n";
+    }
+
+    result = registerResource(m_startCollectionHandle, m_startCollectionUri,
+            m_startCollectionTypes[0], m_startCollectionInterfaces[0], callback,
+            OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (startCollection) was unsuccessful\n";
+    }
+
+    result = bindResource(m_diagnosticsHandle, m_factoryResetHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding installedLocation resource to room was unsuccessful\n";
+    }
+
+    result = bindResource(m_diagnosticsHandle, m_rebootHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding time resource to room was unsuccessful\n";
+    }
+
+    result = bindResource(m_diagnosticsHandle, m_startCollectionHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding network resource to room was unsuccessful\n";
+    }
+
+    thread exec(
+            std::function< void(int second) >(
+                    std::bind(&DiagnosticsCollection::diagnosticsMonitor, this,
+                            std::placeholders::_1)), 10); // every 10 seconds
+    exec.detach();
+
+    std::cout << "Diagnostics Collection is Created!\n";
+}
+
+void DiagnosticsCollection::setDiagnosticsRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_diagnosticsValue = value;
+
+        std::cout << "\t\t\t\t" << "m_diagnosticsValue: " << m_diagnosticsValue << std::endl;
+    }
+}
+
+void DiagnosticsCollection::setFactoryResetRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_factoryResetValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_factoryResetValue << std::endl;
+    }
+}
+
+void DiagnosticsCollection::setRebootRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_rebootValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_rebootValue << std::endl;
+    }
+}
+
+void DiagnosticsCollection::setStartCollectionRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_startCollectionValue = value;
+
+        std::cout << "\t\t\t\t" << "value: " << m_startCollectionValue << std::endl;
+    }
+}
+
+OCRepresentation DiagnosticsCollection::getFactoryResetRepresentation()
+{
+    m_factoryResetRep.setValue("value", m_factoryResetValue);
+
+    return m_factoryResetRep;
+}
+
+OCRepresentation DiagnosticsCollection::getRebootRepresentation()
+{
+    m_rebootRep.setValue("value", m_rebootValue);
+
+    return m_rebootRep;
+}
+
+OCRepresentation DiagnosticsCollection::getStartCollectionRepresentation()
+{
+    m_startCollectionRep.setValue("value", m_startCollectionValue);
+
+    return m_startCollectionRep;
+}
+
+OCRepresentation DiagnosticsCollection::getDiagnosticsRepresentation()
+{
+    m_diagnosticsRep.clearChildren();
+
+    m_diagnosticsRep.addChild(getFactoryResetRepresentation());
+    m_diagnosticsRep.addChild(getRebootRepresentation());
+    m_diagnosticsRep.addChild(getStartCollectionRepresentation());
+
+    m_diagnosticsRep.setValue("value", m_diagnosticsValue);
+
+    return m_diagnosticsRep;
+}
+
+std::string DiagnosticsCollection::getDiagnosticsUri()
+{
+    return m_diagnosticsUri;
+}
+
+std::string DiagnosticsCollection::getFactoryResetUri()
+{
+    return m_factoryResetUri;
+}
+
+std::string DiagnosticsCollection::getRebootUri()
+{
+    return m_rebootUri;
+}
+
+std::string DiagnosticsCollection::getStartCollectionUri()
+{
+    return m_startCollectionUri;
+}
+
+void DiagnosticsCollection::diagnosticsMonitor(int second)
+{
+    while (1)
+    {
+        sleep(second);
+
+        if (m_rebootValue == "true")
+        {
+            int res;
+            std::cout << "Reboot will be soon..." << std::endl;
+            m_rebootValue = defaultReboot;
+            res = system("sudo reboot"); // System reboot
+
+            std::cout << "return: " << res << std::endl;
+
+        }
+        else if (m_factoryResetValue == "true")
+        {
+            std::cout << "Factory Reset will be soon..." << std::endl;
+            m_factoryResetValue = defaultFactoryReset;
+            factoryReset();
+        }
+    }
+}
diff --git a/service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.h b/service/things-manager/sampleapp/linux/configuration/DiagnosticsCollection.h
new file mode 100644 (file)
index 0000000..df4c83e
--- /dev/null
@@ -0,0 +1,150 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+
+static std::string defaultDiagnosticsValue = "false";
+static std::string defaultFactoryReset = "false";
+static std::string defaultReboot = "false";
+static std::string defaultStartCollection = "false";
+
+class DiagnosticsCollection
+{
+public:
+
+    // diagnostics members
+    std::string m_diagnosticsUri;
+    std::string m_diagnosticsValue;
+    std::vector< std::string > m_diagnosticsTypes;
+    std::vector< std::string > m_diagnosticsInterfaces;
+    OCResourceHandle m_diagnosticsHandle;
+    OCRepresentation m_diagnosticsRep;
+
+    // factory reset members
+    std::string m_factoryResetUri;
+    std::string m_factoryResetValue;
+    std::vector< std::string > m_factoryResetTypes;
+    std::vector< std::string > m_factoryResetInterfaces;
+    OCResourceHandle m_factoryResetHandle;
+    OCRepresentation m_factoryResetRep;
+
+    // reboot members
+    std::string m_rebootUri;
+    std::string m_rebootValue;
+    std::vector< std::string > m_rebootTypes;
+    std::vector< std::string > m_rebootInterfaces;
+    OCResourceHandle m_rebootHandle;
+    OCRepresentation m_rebootRep;
+
+    // startcollection members
+    std::string m_startCollectionUri;
+    std::string m_startCollectionValue;
+    std::vector< std::string > m_startCollectionTypes;
+    std::vector< std::string > m_startCollectionInterfaces;
+    OCResourceHandle m_startCollectionHandle;
+    OCRepresentation m_startCollectionRep;
+
+public:
+    /// Constructor
+    DiagnosticsCollection() :
+            m_diagnosticsValue(defaultDiagnosticsValue), m_factoryResetValue(defaultFactoryReset), m_rebootValue(
+                    defaultReboot), m_startCollectionValue(defaultStartCollection)
+    {
+        m_factoryResetUri = "/oic/diag/0/factoryReset"; // URI of the resource
+        m_factoryResetTypes.push_back("oic.diag.factoryReset"); // resource type name.
+        m_factoryResetInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_factoryResetRep.setUri(m_factoryResetUri);
+        m_factoryResetRep.setResourceTypes(m_factoryResetTypes);
+        m_factoryResetRep.setResourceInterfaces(m_factoryResetInterfaces);
+        m_factoryResetRep.setValue("value", m_factoryResetValue);
+        m_factoryResetHandle = NULL;
+
+        m_rebootUri = "/oic/diag/0/reboot"; // URI of the resource
+        m_rebootTypes.push_back("oic.diag.reboot"); // resource type name.
+        m_rebootInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_rebootRep.setUri(m_rebootUri);
+        m_rebootRep.setResourceTypes(m_rebootTypes);
+        m_rebootRep.setResourceInterfaces(m_rebootInterfaces);
+        m_rebootRep.setValue("value", m_rebootValue);
+        m_rebootHandle = NULL;
+
+        m_startCollectionUri = "/oic/diag/0/startCollection"; // URI of the resource
+        m_startCollectionTypes.push_back("oic.diag.startCollection"); // resource type name.
+        m_startCollectionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_startCollectionRep.setUri(m_startCollectionUri);
+        m_startCollectionRep.setResourceTypes(m_startCollectionTypes);
+        m_startCollectionRep.setResourceInterfaces(m_startCollectionInterfaces);
+        m_startCollectionRep.setValue("value", m_startCollectionValue);
+        m_startCollectionHandle = NULL;
+
+        m_diagnosticsUri = "/oic/diag"; // URI of the resource
+        m_diagnosticsTypes.push_back("oic.diag"); // resource type name.
+        m_diagnosticsInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_diagnosticsInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_diagnosticsInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_diagnosticsRep.setValue("value", m_diagnosticsValue);
+        m_diagnosticsRep.setUri(m_diagnosticsUri);
+        m_diagnosticsRep.setResourceTypes(m_diagnosticsTypes);
+        m_diagnosticsRep.setResourceInterfaces(m_diagnosticsInterfaces);
+        m_diagnosticsHandle = NULL;
+    }
+    ;
+
+    /// This function internally calls registerResource API.
+    void createResources(ResourceEntityHandler callback);
+
+    void setDiagnosticsRepresentation(OCRepresentation& rep);
+    void setFactoryResetRepresentation(OCRepresentation& rep);
+    void setRebootRepresentation(OCRepresentation& rep);
+    void setStartCollectionRepresentation(OCRepresentation& rep);
+
+    OCRepresentation getDiagnosticsRepresentation();
+    OCRepresentation getFactoryResetRepresentation();
+    OCRepresentation getRebootRepresentation();
+    OCRepresentation getStartCollectionRepresentation();
+
+    std::string getDiagnosticsUri();
+    std::string getFactoryResetUri();
+    std::string getRebootUri();
+    std::string getStartCollectionUri();
+
+    void diagnosticsMonitor(int second);
+
+    std::function< void() > factoryReset;
+};
+
diff --git a/service/things-manager/sampleapp/linux/configuration/FactorySetCollection.cpp b/service/things-manager/sampleapp/linux/configuration/FactorySetCollection.cpp
new file mode 100644 (file)
index 0000000..d050096
--- /dev/null
@@ -0,0 +1,141 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+#include "FactorySetCollection.h"
+
+using namespace OC;
+
+/// This function internally calls registerResource API.
+void FactorySetCollection::createResources(ResourceEntityHandler callback)
+{
+    using namespace OC::OCPlatform;
+
+    if (callback == NULL)
+    {
+        std::cout << "callback should be binded\t";
+        return;
+    }
+
+    // This will internally create and register the resource.
+    OCStackResult result = registerResource(m_factorySetHandle, m_factorySetUri,
+            m_factorySetTypes[0], m_factorySetInterfaces[0], callback,
+            OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (configuration) was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_factorySetHandle, m_factorySetInterfaces[1]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = bindInterfaceToResource(m_factorySetHandle, m_factorySetInterfaces[2]);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding TypeName to Resource was unsuccessful\n";
+    }
+
+    result = registerResource(m_configurationCollectionHandle, m_configurationCollectionUri,
+            m_configurationCollectionTypes[0], m_configurationCollectionInterfaces[0], callback,
+            OC_DISCOVERABLE | OC_OBSERVABLE);
+
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Resource creation (installedLocation) was unsuccessful\n";
+    }
+
+    result = bindResource(m_factorySetHandle, m_configurationCollectionHandle);
+    if (OC_STACK_OK != result)
+    {
+        std::cout << "Binding installedLocation resource to room was unsuccessful\n";
+    }
+
+    defaultConfigurationCollection = new ConfigurationCollection(defaultConfigurationURIPrefix,
+            defaultConfigurationResourceTypePrefix);
+    //defaultConfigurationCollection->bindEntityHander(callback);
+    defaultConfigurationCollection->createResources(callback);
+
+    std::cout << "FactorySet Collection is Created!\n";
+}
+
+void FactorySetCollection::setFactorySetRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("value", value))
+    {
+        m_factorySetValue = value;
+
+        std::cout << "\t\t\t\t" << "m_factorySetValue: " << m_factorySetValue << std::endl;
+    }
+}
+
+void FactorySetCollection::setConfigurationCollectionRepresentation(OCRepresentation& rep)
+{
+    string value;
+
+    if (rep.getValue("link", value))
+    {
+        // NOT ALLOWED
+
+        std::cout << "\t\t\t\t" << "link: " << m_configurationCollectionLink << std::endl;
+    }
+}
+
+OCRepresentation FactorySetCollection::getConfigurationCollectionRepresentation()
+{
+    m_configurationCollectionRep.setValue("link", m_configurationCollectionLink);
+
+    return m_configurationCollectionRep;
+}
+
+OCRepresentation FactorySetCollection::getFactorySetRepresentation()
+{
+    m_factorySetRep.clearChildren();
+
+    m_factorySetRep.addChild(getConfigurationCollectionRepresentation());
+
+    m_factorySetRep.setValue("value", m_factorySetValue);
+
+    return m_factorySetRep;
+}
+
+std::string FactorySetCollection::getFactorySetUri()
+{
+    return m_factorySetUri;
+}
+
+std::string FactorySetCollection::getConfigurationCollectionUri()
+{
+    return m_configurationCollectionUri;
+}
diff --git a/service/things-manager/sampleapp/linux/configuration/FactorySetCollection.h b/service/things-manager/sampleapp/linux/configuration/FactorySetCollection.h
new file mode 100644 (file)
index 0000000..bc20a71
--- /dev/null
@@ -0,0 +1,120 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+#include "ConfigurationCollection.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function< OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+
+extern std::string defaultFactorySetValue;
+static std::string defaultConfigurationCollectionLink = "/factorySet/oic/con";
+
+static std::string defaultConfigurationURIPrefix = "/factorySet/oic/con";
+static std::string defaultConfigurationResourceTypePrefix = "factorySet.oic.con";
+
+class FactorySetCollection
+{
+public:
+
+    ConfigurationCollection *defaultConfigurationCollection;
+
+public:
+
+    // diagnostics members
+    std::string m_factorySetUri;
+    std::string m_factorySetValue;
+    std::vector< std::string > m_factorySetTypes;
+    std::vector< std::string > m_factorySetInterfaces;
+    OCResourceHandle m_factorySetHandle;
+    OCRepresentation m_factorySetRep;
+
+    // Configuration members
+    std::string m_configurationCollectionUri;
+    std::string m_configurationCollectionLink;
+    std::vector< std::string > m_configurationCollectionTypes;
+    std::vector< std::string > m_configurationCollectionInterfaces;
+    OCResourceHandle m_configurationCollectionHandle;
+    OCRepresentation m_configurationCollectionRep;
+
+public:
+    /// Constructor
+    FactorySetCollection() :
+            m_factorySetValue(defaultFactorySetValue), m_configurationCollectionLink(
+                    defaultConfigurationCollectionLink)
+    {
+        m_configurationCollectionUri = "/factorySet/0/con"; // URI of the resource
+        m_configurationCollectionTypes.push_back("factorySet.con"); // resource type name.
+        m_configurationCollectionInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+
+        m_configurationCollectionRep.setUri(m_configurationCollectionUri);
+        m_configurationCollectionRep.setResourceTypes(m_configurationCollectionTypes);
+        m_configurationCollectionRep.setResourceInterfaces(m_configurationCollectionInterfaces);
+        m_configurationCollectionRep.setValue("link", m_configurationCollectionLink);
+        m_configurationCollectionHandle = NULL;
+
+        m_factorySetUri = "/factorySet"; // URI of the resource
+        m_factorySetTypes.push_back("factorySet"); // resource type name.
+        m_factorySetInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_factorySetInterfaces.push_back(BATCH_INTERFACE); // resource interface.
+        m_factorySetInterfaces.push_back(LINK_INTERFACE); // resource interface.
+        m_factorySetRep.setValue("value", m_factorySetValue);
+        m_factorySetRep.setUri(m_factorySetUri);
+        m_factorySetRep.setResourceTypes(m_factorySetTypes);
+        m_factorySetRep.setResourceInterfaces(m_factorySetInterfaces);
+        m_factorySetHandle = NULL;
+
+        defaultConfigurationCollection = NULL;
+    }
+    ;
+
+    ~FactorySetCollection()
+    {
+        if (defaultConfigurationCollection != NULL)
+            free(defaultConfigurationCollection);
+    }
+    ;
+
+    /// This function internally calls registerResource API.
+    void createResources(ResourceEntityHandler callback);
+
+    void setFactorySetRepresentation(OCRepresentation& rep);
+    void setConfigurationCollectionRepresentation(OCRepresentation& rep);
+
+    OCRepresentation getFactorySetRepresentation();
+    OCRepresentation getConfigurationCollectionRepresentation();
+
+    std::string getFactorySetUri();
+    std::string getConfigurationCollectionUri();
+
+};
+
diff --git a/service/things-manager/sampleapp/linux/configuration/SConscript b/service/things-manager/sampleapp/linux/configuration/SConscript
new file mode 100644 (file)
index 0000000..d4a8c5d
--- /dev/null
@@ -0,0 +1,34 @@
+##
+# linux sample app  build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+linux_sample_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
+linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack', 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+
+######################################################################
+#build sampleapp
+######################################################################
+conserver = linux_sample_env.Program('con-server', ['ConfigurationCollection.cpp', 'DiagnosticsCollection.cpp', 'FactorySetCollection.cpp', 'con-server.cpp'])
+conclient = linux_sample_env.Program('con-client', 'con-client.cpp')
+bootstrapserver = linux_sample_env.Program('bootstrapserver', 'bootstrapserver.cpp')
+Alias("ConServerApp", conserver)
+Alias("ConCleintApp", conclient)
+Alias("BootstrapServerApp", bootstrapserver)
+env.AppendTarget('ConServerApp')
+env.AppendTarget('ConClientApp')
+env.AppendTarget('BootstrapServerApp')
diff --git a/service/things-manager/sampleapp/linux/configuration/bootstrapserver.cpp b/service/things-manager/sampleapp/linux/configuration/bootstrapserver.cpp
new file mode 100644 (file)
index 0000000..e53f61c
--- /dev/null
@@ -0,0 +1,237 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+
+#include <pthread.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+
+// Forward declaring the entityHandler (bootstrap)
+bool prepareResponse(std::shared_ptr< OCResourceRequest > request);
+OCStackResult sendResponse(std::shared_ptr< OCResourceRequest > pRequest);
+OCEntityHandlerResult entityHandlerBootstrap(std::shared_ptr< OCResourceRequest > request);
+
+#define DefaultConfigurationValue "Configuration Collection"
+#define DefaultRegionValue "Seoul, Korea"
+#define DefaultTimeValue "Time Collection"
+#define DefaultCurrentTimeValue "00:00:00"
+#define DefaultNetworkValue "Network Collection"
+#define DefaultIPAddressValue "192.168.0.2"
+#define DefaultSecurityValue "SecurityValue"
+#define DefaultModeValue "NoSec"
+#define DefaultFactorySetValue "FactorySet Value"
+
+class BootstrapResource
+{
+public:
+    // Room members
+    std::string m_bootstrapUri;
+    std::vector< std::string > m_bootstrapTypes;
+    std::vector< std::string > m_bootstrapInterfaces;
+    OCResourceHandle m_bootstrapHandle;
+    OCRepresentation m_bootstrapRep;
+
+public:
+    /// Constructor
+    BootstrapResource()
+    {
+        m_bootstrapUri = "/bootstrap"; // URI of the resource
+        m_bootstrapTypes.push_back("bootstrap"); // resource type name. In this case, it is light
+        m_bootstrapInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+        m_bootstrapRep.setUri(m_bootstrapUri);
+        m_bootstrapRep.setResourceTypes(m_bootstrapTypes);
+        m_bootstrapRep.setResourceInterfaces(m_bootstrapInterfaces);
+        m_bootstrapHandle = NULL;
+    }
+
+    /// This function internally calls registerResource API.
+    void createResources()
+    {
+        using namespace OC::OCPlatform;
+        // This will internally create and register the resource.
+        OCStackResult result = registerResource(m_bootstrapHandle, m_bootstrapUri,
+                m_bootstrapTypes[0], m_bootstrapInterfaces[0], entityHandlerBootstrap,
+                OC_DISCOVERABLE | OC_OBSERVABLE);
+
+        if (OC_STACK_OK != result)
+        {
+            cout << "Resource creation (room) was unsuccessful\n";
+        }
+    }
+
+    void setBootstrapRepresentation(OCRepresentation& rep)
+    {
+        // Not allowed
+    }
+
+    OCRepresentation getBootstrapRepresentation()
+    {
+        m_bootstrapRep.setValue< std::string >("regionValue", DefaultRegionValue);
+        m_bootstrapRep.setValue< std::string >("timeValue", DefaultTimeValue);
+        m_bootstrapRep.setValue< std::string >("currentTimeValue", DefaultCurrentTimeValue);
+        m_bootstrapRep.setValue< std::string >("networkValue", DefaultNetworkValue);
+        m_bootstrapRep.setValue< std::string >("IPAddressValue", DefaultIPAddressValue);
+        m_bootstrapRep.setValue< std::string >("securityValue", DefaultSecurityValue);
+        m_bootstrapRep.setValue< std::string >("modeValue", DefaultModeValue);
+        m_bootstrapRep.setValue< std::string >("configurationValue", DefaultConfigurationValue);
+        m_bootstrapRep.setValue< std::string >("factorySetValue", DefaultFactorySetValue);
+
+        return m_bootstrapRep;
+    }
+};
+
+// Create the instance of the resource class (in this case instance of class 'RoomResource').
+BootstrapResource myBootstrapResource;
+
+// This function prepares a response for any incoming request to Light resource.
+bool prepareResponse(std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "\tIn Server CPP prepareResponse:\n";
+    bool result = false;
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        if (requestFlag == RequestHandlerFlag::InitFlag)
+        {
+            cout << "\t\trequestFlag : Init\n";
+
+            // entity handler to perform resource initialization operations
+        }
+        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\t\trequestFlag : Request\n";
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                cout << "\t\t\trequestType : GET\n";
+                // GET operations are directly handled while sending the response
+                // in the sendLightResponse function
+                result = true;
+            }
+            else if (requestType == "PUT")
+            {
+                cout << "\t\t\trequestType : PUT\n";
+
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                // Do related operations related to PUT request
+                myBootstrapResource.setBootstrapRepresentation(rep);
+                result = true;
+            }
+            else if (requestType == "POST")
+            {
+                // POST request operations
+            }
+            else if (requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        {
+            cout << "\t\trequestFlag : Observer\n";
+        }
+    }
+    else
+    {
+        std::cout << "Request invalid" << std::endl;
+    }
+
+    return result;
+}
+
+OCStackResult sendResponse(std::shared_ptr< OCResourceRequest > pRequest)
+{
+    auto pResponse = std::make_shared< OC::OCResourceResponse >();
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+    pResponse->setResourceRepresentation(myBootstrapResource.getBootstrapRepresentation());
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    return OCPlatform::sendResponse(pResponse);
+}
+
+OCEntityHandlerResult entityHandlerBootstrap(std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "\tIn Server CPP (entityHandlerBootstrap) entity handler:\n";
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    if (prepareResponse(request))
+    {
+        if (OC_STACK_OK == sendResponse(request))
+        {
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            std::cout << "sendResponse failed." << std::endl;
+        }
+    }
+    else
+    {
+        std::cout << "PrepareResponse failed." << std::endl;
+    }
+    return ehResult;
+}
+
+int main()
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0",
+    // By setting to "0.0.0.0", it binds to all available interfaces
+            0,// Uses randomly available port
+            OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    try
+    {
+
+        myBootstrapResource.createResources();
+
+        // Perform app tasks
+        while (true)
+        {
+            // some tasks
+        }
+    }
+    catch (OCException e)
+    {
+        std::cout << "Exception in main: " << e.what();
+    }
+
+    // No explicit call to stop the platform.
+    // When OCPlatform destructor is invoked, internally we do platform cleanup
+}
+
diff --git a/service/things-manager/sampleapp/linux/configuration/con-client.cpp b/service/things-manager/sampleapp/linux/configuration/con-client.cpp
new file mode 100644 (file)
index 0000000..278c3e2
--- /dev/null
@@ -0,0 +1,449 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// OCClient.cpp : Defines the entry point for the console application.
+//
+#include <string>
+#include <cstdlib>
+#include <pthread.h>
+#include <map>
+#include <vector>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+using namespace OIC;
+
+int g_Steps = 0;
+int isWaiting = 0; //0: none to wait, 1: wait for the response of "getConfigurationValue"
+
+static ThingsManager* g_thingsmanager;
+
+OCResourceHandle configurationCollectionHandle;
+std::shared_ptr< OCResource > g_configurationCollection; // for a group of multiple resources
+std::shared_ptr< OCResource > g_configurationResource; // For a single resource
+
+OCResourceHandle diagnosticsCollectionHandle;
+std::shared_ptr< OCResource > g_diagnosticsCollection; // for a group of multiple resources
+std::shared_ptr< OCResource > g_diagnosticsResource; // For a single resource
+
+OCResourceHandle setCollectionHandle;
+std::shared_ptr< OCResource > g_setCollection; // for a group of multiple resources
+std::shared_ptr< OCResource > g_setResource; // For a single resource
+
+std::map< std::string, std::shared_ptr< OCResource > > resourceTable;
+std::vector< OCResourceHandle > resourceHandleVector;
+
+typedef std::function<
+        void(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode) > ConfigurationCallback;
+typedef std::function<
+        void(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode) > DiagnosticsCallback;
+
+typedef std::string ConfigurationName;
+typedef std::string ConfigurationValue;
+
+void onReboot(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    std::cout << "\t\tReboot:" << rep.getValue< std::string >("value") << std::endl;
+
+    isWaiting = 0;
+}
+
+void onFactoryReset(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+        const int eCode)
+{
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    std::cout << "\t\tFactoryReset:" << rep.getValue< std::string >("value") << std::endl;
+    isWaiting = 0;
+}
+
+void onUpdate(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    std::cout << "\t\tvalue:" << rep.getValue< std::string >("value") << std::endl;
+
+    isWaiting = 0;
+}
+
+void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    if (rep.hasAttribute("value"))
+        std::cout << "\t\tvalue:" << rep.getValue< std::string >("value") << std::endl;
+    else if (rep.hasAttribute("link"))
+        std::cout << "\t\tlink:" << rep.getValue< std::string >("link") << std::endl;
+
+    std::vector< OCRepresentation > children = rep.getChildren();
+
+    for (auto oit = children.begin(); oit != children.end(); ++oit)
+    {
+        std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+
+        if (oit->hasAttribute("value"))
+            std::cout << "\t\tvalue:" << oit->getValue< std::string >("value") << std::endl;
+        else if (oit->hasAttribute("link"))
+            std::cout << "\t\tlink:" << oit->getValue< std::string >("link") << std::endl;
+    }
+
+    isWaiting = 0;
+}
+
+// Callback to found collection resource
+void onFoundCollectionResource(std::vector< std::shared_ptr< OCResource > > resources)
+{
+
+    std::string resourceURI;
+    std::string hostAddress;
+    try
+    {
+        // Do some operations with resource object.
+        for (unsigned int i = 0; i < resources.size(); ++i)
+        {
+            std::shared_ptr< OCResource > resource = resources.at(i);
+
+            if (resource)
+            {
+                if (resource->uri() == "/core/a/configuration/resourceset")
+                    g_configurationCollection = resource;
+                else if (resource->uri() == "/core/a/diagnostics/resourceset")
+                    g_diagnosticsCollection = resource;
+                else if (resource->uri() == "/core/a/factoryset/resourceset")
+                    g_setCollection = resource;
+                else
+                {
+                    isWaiting = 0;
+                    return;
+                }
+            }
+            else
+            {
+                // Resource is invalid
+                std::cout << "Resource is invalid" << std::endl;
+            }
+        }
+
+    }
+    catch (std::exception& e)
+    {
+        //log(e.what());
+    }
+
+    if (g_configurationCollection != NULL && g_diagnosticsCollection != NULL
+            && g_setCollection != NULL)
+        isWaiting = 0;
+}
+
+// Callback to found resources
+void onFoundCandidateCollection(std::vector< std::shared_ptr< OCResource > > resources)
+{
+
+    std::string resourceURI;
+    std::string hostAddress;
+
+    static bool flagForCon = false, flagForDiag = false, flagForSet = false;
+
+    try
+    {
+        // Do some operations with resource object.
+        for (unsigned int i = 0; i < resources.size(); ++i)
+        {
+            std::shared_ptr< OCResource > resource = resources.at(i);
+
+            if (resource)
+            {
+                // Check if the resource is new one. If so, store it.
+
+                std::map< std::string, std::shared_ptr< OCResource > >::iterator iter =
+                        resourceTable.find(resource->host() + resource->uri());
+
+                if (iter == resourceTable.end()) // new one
+                {
+                    resourceTable[resource->host() + resource->uri()] = resource;
+
+                    OCResourceHandle foundResourceHandle;
+                    OCStackResult result = OCPlatform::registerResource(foundResourceHandle,
+                            resource);
+                    std::cout << "\tResource ( " << resource->host() << " ) is registed!\t"
+                            << std::endl;
+                    if (result == OC_STACK_OK)
+                    {
+                        if (resource->uri() == "/oic/con")
+                        {
+                            flagForCon = true;
+                            OCPlatform::bindResource(configurationCollectionHandle,
+                                    foundResourceHandle);
+                            if (g_configurationResource == NULL)
+                                g_configurationResource = resource;
+                        }
+                        else if (resource->uri() == "/oic/diag")
+                        {
+                            flagForDiag = true;
+                            OCPlatform::bindResource(diagnosticsCollectionHandle,
+                                    foundResourceHandle);
+                            if (g_diagnosticsResource == NULL)
+                                g_diagnosticsResource = resource;
+                        }
+                        else if (resource->uri() == "/factorySet")
+                        {
+                            flagForSet = true;
+                            OCPlatform::bindResource(setCollectionHandle, foundResourceHandle);
+                            if (g_setResource == NULL)
+                                g_setResource = resource;
+                        }
+
+                        resourceHandleVector.push_back(foundResourceHandle);
+                    }
+                    else
+                    {
+                        cout << "\tresource Error!" << endl;
+                    }
+
+                }
+
+            }
+            else
+            {
+                // Resource is invalid
+                std::cout << "Resource is invalid" << std::endl;
+            }
+        }
+
+    }
+    catch (std::exception& e)
+    {
+        //log(e.what());
+    }
+
+    if (flagForCon && flagForDiag && flagForSet)
+        isWaiting = 0;
+}
+
+int main(int argc, char* argv[])
+{
+
+    //**************************************************************
+    // STEP 0
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    g_thingsmanager = new ThingsManager();
+
+    //**************************************************************
+
+    while (true)
+    {
+
+        if (isWaiting > 0)
+            continue;
+
+        isWaiting = 0;
+
+        cout << endl << endl << "(0) Quit" << std::endl;
+        cout << "(1) Find all resources(URI: /oic/con, /oic/diag, /factoryset)" << std::endl;
+        cout << "(2) Find all groups" << std::endl;
+        cout << "(3) Get a new value (of \"Configuration\" Collection)" << std::endl;
+        cout << "(4) Update a value (of \"Region\" Resource)" << std::endl;
+        cout << "(5) Get a value (for \"Region\" Resource)" << std::endl;
+        cout << "(6) FactoryReset (for the group)" << std::endl;
+        cout << "(7) Reboot (for the group)" << std::endl;
+        cout << "(10) Show Configuration Units" << std::endl;
+
+        cin >> g_Steps;
+        //
+        if (g_Steps == 0)
+            break;
+        else if (g_Steps == 1)
+        {
+            std::vector< std::string > types;
+            { // For Registering a collection resource for configuration resources
+
+                string resourceURI = "/core/a/configuration/resourceset";
+                string resourceTypeName = "core.configuration.resourceset";
+                string resourceInterface = BATCH_INTERFACE;
+
+                if (configurationCollectionHandle != NULL)
+                {
+                    std::cout << "already exists" << std::endl;
+                    continue;
+                }
+
+                OCPlatform::registerResource(configurationCollectionHandle, resourceURI,
+                        resourceTypeName, resourceInterface, NULL,
+                        //&entityHandler, // entityHandler
+                        OC_DISCOVERABLE);
+
+                OCPlatform::bindInterfaceToResource(configurationCollectionHandle, GROUP_INTERFACE);
+                OCPlatform::bindInterfaceToResource(configurationCollectionHandle,
+                        DEFAULT_INTERFACE);
+
+                // instead of registration
+                types.push_back("oic.con");
+                std::cout << "Finding Configuration Resource... " << std::endl;
+            }
+
+            { // For Registering a collection resource for diagnostics resources
+
+                string resourceURI = "/core/a/diagnostics/resourceset";
+                string resourceTypeName = "core.diagnostics.resourceset";
+                string resourceInterface = BATCH_INTERFACE;
+
+                if (diagnosticsCollectionHandle != NULL)
+                {
+                    std::cout << "already exists" << std::endl;
+                    continue;
+                }
+
+                OCPlatform::registerResource(diagnosticsCollectionHandle, resourceURI,
+                        resourceTypeName, resourceInterface, NULL,
+                        //&entityHandler, // entityHandler
+                        OC_DISCOVERABLE);
+
+                OCPlatform::bindInterfaceToResource(diagnosticsCollectionHandle, GROUP_INTERFACE);
+                OCPlatform::bindInterfaceToResource(diagnosticsCollectionHandle, DEFAULT_INTERFACE);
+
+                // instead of registration
+                types.push_back("oic.diag");
+                std::cout << "Finding Diagnostics Resource... " << std::endl;
+
+            }
+
+            { // For Registering a collection resource for set resources
+
+                string resourceURI = "/core/a/factoryset/resourceset";
+                string resourceTypeName = "core.factoryset.resourceset";
+                string resourceInterface = BATCH_INTERFACE;
+
+                if (setCollectionHandle != NULL)
+                {
+                    std::cout << "already exists" << std::endl;
+                    continue;
+                }
+
+                OCPlatform::registerResource(setCollectionHandle, resourceURI, resourceTypeName,
+                        resourceInterface, NULL,
+                        //&entityHandler, // entityHandler
+                        OC_DISCOVERABLE);
+
+                OCPlatform::bindInterfaceToResource(setCollectionHandle, GROUP_INTERFACE);
+                OCPlatform::bindInterfaceToResource(setCollectionHandle, DEFAULT_INTERFACE);
+
+                // instead of registration
+                types.push_back("factorySet");
+                std::cout << "Finding Set Resource... " << std::endl;
+            }
+
+            g_thingsmanager->findCandidateResources(types, &onFoundCandidateCollection, 5);
+
+            isWaiting = 1;
+        }
+        else if (g_Steps == 2) // make a group with found things
+        {
+            std::vector< std::string > types;
+            types.push_back("core.configuration.resourceset");
+            types.push_back("core.diagnostics.resourceset");
+            types.push_back("core.factoryset.resourceset");
+
+            g_thingsmanager->findCandidateResources(types, &onFoundCollectionResource, 5);
+
+            std::cout << "Finding Collection resource... " << std::endl;
+            isWaiting = 1;
+
+        }
+        else if (g_Steps == 3)
+        {
+            // get a value
+
+            ConfigurationName name = "configuration";
+
+            std::cout << "For example, get configuration collection's value" << std::endl;
+
+            std::vector< ConfigurationName > configurations;
+
+            configurations.push_back(name);
+
+            if (g_thingsmanager->getConfigurations(g_configurationResource, configurations, &onGet)
+                    != OC_STACK_ERROR)
+                isWaiting = 1;
+        }
+        else if (g_Steps == 4)
+        {
+            ConfigurationName name = "region";
+            ConfigurationValue value = "U.S.A (new region)";
+
+            std::cout << "For example, change region resource's value" << std::endl;
+            std::cout << g_configurationCollection->uri() << std::endl;
+
+            std::map< ConfigurationName, ConfigurationValue > configurations;
+
+            configurations.insert(std::make_pair(name, value));
+
+            if (g_thingsmanager->updateConfigurations(g_configurationCollection, configurations,
+                    &onUpdate) != OC_STACK_ERROR)
+                isWaiting = 1;
+        }
+        else if (g_Steps == 5)
+        {
+            // get a value
+
+            ConfigurationName name = "region";
+
+            std::cout << "For example, get region resource's value" << std::endl;
+
+            std::vector< ConfigurationName > configurations;
+
+            configurations.push_back(name);
+
+            if (g_thingsmanager->getConfigurations(g_configurationCollection, configurations,
+                    &onGet) != OC_STACK_ERROR)
+                isWaiting = 1;
+        }
+        else if (g_Steps == 6)
+        {
+            // factory reset
+            if (g_thingsmanager->factoryReset(g_diagnosticsCollection, &onFactoryReset)
+                    != OC_STACK_ERROR)
+                isWaiting = 1;
+        }
+        else if (g_Steps == 7)
+        {
+            // reboot
+            if (g_thingsmanager->reboot(g_diagnosticsCollection, &onReboot) != OC_STACK_ERROR)
+                isWaiting = 1;
+        }
+        else if (g_Steps == 10)
+        {
+            std::cout << g_thingsmanager->getListOfSupportedConfigurationUnits() << std::endl;
+
+        }
+
+    }
+
+    return 0;
+}
+
diff --git a/service/things-manager/sampleapp/linux/configuration/con-server.cpp b/service/things-manager/sampleapp/linux/configuration/con-server.cpp
new file mode 100644 (file)
index 0000000..6b26437
--- /dev/null
@@ -0,0 +1,356 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample shows how one could create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+#include "ConfigurationCollection.h"
+#include "DiagnosticsCollection.h"
+#include "FactorySetCollection.h"
+
+using namespace OC;
+using namespace OIC;
+
+const int SUCCESS_RESPONSE = 0;
+int g_Steps = 0;
+int isWaiting = 0;
+
+// Default system configuration value's variables
+// The variable's names should be same as the names of "extern" variables defined in
+// "ConfigurationCollection.h"
+std::string defaultRegionValue;
+std::string defaultTimeValue;
+std::string defaultCurrentTimeValue;
+std::string defaultNetworkValue;
+std::string defaultIPAddressValue;
+std::string defaultSecurityValue;
+std::string defaultModeValue;
+std::string defaultConfigurationValue;
+std::string defaultFactorySetValue;
+
+static ThingsManager* g_thingsmanager;
+
+// Forward declaring the entityHandler (Configuration)
+bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request);
+OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest);
+OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request);
+
+ConfigurationCollection *myConfigurationCollection;
+DiagnosticsCollection *myDiagnosticsCollection;
+FactorySetCollection *myFactorySetCollection;
+
+typedef std::function< void(OCRepresentation&) > putFunc;
+typedef std::function< OCRepresentation(void) > getFunc;
+
+getFunc getGetFunction(std::string uri)
+{
+    getFunc res = NULL;
+
+    if (uri == myConfigurationCollection->getTimeUri())
+    {
+        res = std::bind(&ConfigurationCollection::getTimeRepresentation, myConfigurationCollection);
+    }
+    else if (uri == myConfigurationCollection->getConfigurationUri())
+    {
+        res = std::bind(&ConfigurationCollection::getConfigurationRepresentation,
+                myConfigurationCollection);
+    }
+    else if (uri == myConfigurationCollection->myTimeCollection->getCurrentTimeUri())
+    {
+        res = std::bind(&TimeCollection::getCurrentTimeRepresentation,
+                myConfigurationCollection->myTimeCollection);
+    }
+    else if (uri == myConfigurationCollection->getRegionUri())
+    {
+        res = std::bind(&ConfigurationCollection::getRegionRepresentation,
+                myConfigurationCollection);
+    }
+    else if (uri == myDiagnosticsCollection->getFactoryResetUri())
+    {
+        res = std::bind(&DiagnosticsCollection::getFactoryResetRepresentation,
+                myDiagnosticsCollection);
+    }
+    else if (uri == myDiagnosticsCollection->getRebootUri())
+    {
+        res = std::bind(&DiagnosticsCollection::getRebootRepresentation, myDiagnosticsCollection);
+    }
+
+    return res;
+}
+
+putFunc getPutFunction(std::string uri)
+{
+    putFunc res = NULL;
+
+    if (uri == myConfigurationCollection->getRegionUri())
+    {
+        res = std::bind(&ConfigurationCollection::setRegionRepresentation,
+                myConfigurationCollection, std::placeholders::_1);
+    }
+    else if (uri == myConfigurationCollection->myTimeCollection->getCurrentTimeUri())
+    {
+        res = std::bind(&TimeCollection::setCurrentTimeRepresentation,
+                myConfigurationCollection->myTimeCollection, std::placeholders::_1);
+    }
+    else if (uri == myDiagnosticsCollection->getFactoryResetUri())
+    {
+        res = std::bind(&DiagnosticsCollection::setFactoryResetRepresentation,
+                myDiagnosticsCollection, std::placeholders::_1);
+    }
+    else if (uri == myDiagnosticsCollection->getRebootUri())
+    {
+        res = std::bind(&DiagnosticsCollection::setRebootRepresentation, myDiagnosticsCollection,
+                std::placeholders::_1);
+    }
+
+    return res;
+}
+
+// This function prepares a response for any incoming request to Light resource.
+bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request)
+{
+    std::cout << "\tIn Server CPP prepareResponseForResource:\n";
+    bool result = false;
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        if (requestFlag == RequestHandlerFlag::InitFlag)
+        {
+            std::cout << "\t\trequestFlag : Init\n";
+
+            // entity handler to perform resource initialization operations
+        }
+        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        {
+            std::cout << "\t\trequestFlag : Request\n";
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                std::cout << "\t\t\trequestType : GET\n";
+                // GET operations are directly handled while sending the response
+                // in the sendLightResponse function
+                result = true;
+            }
+            else if (requestType == "PUT")
+            {
+                std::cout << "\t\t\trequestType : PUT\n";
+                putFunc putFunction;
+                OCRepresentation rep = request->getResourceRepresentation();
+
+                putFunction = getPutFunction(request->getResourceUri());
+
+                // Do related operations related to PUT request
+                putFunction(rep);
+                result = true;
+            }
+            else if (requestType == "POST")
+            {
+                // POST request operations
+            }
+            else if (requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        {
+            std::cout << "\t\trequestFlag : Observer\n";
+        }
+    }
+    else
+    {
+        std::cout << "Request invalid" << std::endl;
+    }
+
+    return result;
+}
+
+OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest)
+{
+    auto pResponse = std::make_shared< OC::OCResourceResponse >();
+
+    // Check for query params (if any)
+    QueryParamsMap queryParamsMap = pRequest->getQueryParameters();
+
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+
+    getFunc getFunction;
+    getFunction = getGetFunction(pRequest->getResourceUri());
+
+    OCRepresentation rep;
+    rep = getFunction();
+
+    auto findRes = queryParamsMap.find("if");
+
+    if (findRes != queryParamsMap.end())
+    {
+        pResponse->setResourceRepresentation(rep, findRes->second);
+    }
+    else
+    {
+        pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+    }
+
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    return OCPlatform::sendResponse(pResponse);
+}
+
+OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request)
+{
+    std::cout << "\tIn Server CPP (entityHandlerForResource) entity handler:\n";
+    OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+    if (prepareResponseForResource(request))
+    {
+        if (OC_STACK_OK == sendResponseForResource(request))
+        {
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            std::cout << "sendResponse failed." << std::endl;
+        }
+    }
+    else
+    {
+        std::cout << "PrepareResponse failed." << std::endl;
+    }
+    return ehResult;
+}
+
+// callback handler on GET request
+void onBootstrap(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    if (eCode == SUCCESS_RESPONSE)
+    {
+        std::cout << "\n\nGET request was successful" << std::endl;
+        std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+        defaultRegionValue = rep.getValue< std::string >("regionValue");
+        defaultTimeValue = rep.getValue< std::string >("timeValue");
+        defaultCurrentTimeValue = rep.getValue< std::string >("currentTimeValue");
+        defaultNetworkValue = rep.getValue< std::string >("networkValue");
+        defaultIPAddressValue = rep.getValue< std::string >("IPAddressValue");
+        defaultSecurityValue = rep.getValue< std::string >("securityValue");
+        defaultModeValue = rep.getValue< std::string >("modeValue");
+        defaultConfigurationValue = rep.getValue< std::string >("configurationValue");
+        defaultFactorySetValue = rep.getValue< std::string >("factorySetValue");
+
+        std::cout << "\tregionValue : " << defaultRegionValue << std::endl;
+        std::cout << "\ttimeValue : " << defaultTimeValue << std::endl;
+        std::cout << "\tcurrentTimeValue : " << defaultCurrentTimeValue << std::endl;
+        std::cout << "\tnetworkValue : " << defaultNetworkValue << std::endl;
+        std::cout << "\tIPAddressValue : " << defaultIPAddressValue << std::endl;
+        std::cout << "\tsecurityValue : " << defaultSecurityValue << std::endl;
+        std::cout << "\tmodeValue : " << defaultModeValue << std::endl;
+        std::cout << "\tconfigurationValue : " << defaultConfigurationValue << std::endl;
+        std::cout << "\tfactorySetValue : " << defaultFactorySetValue << std::endl;
+
+    }
+    else
+    {
+        std::cout << "onGET Response error: " << eCode << std::endl;
+        std::exit(-1);
+    }
+    isWaiting = 0;
+}
+
+int main()
+{
+    //**************************************************************
+    // STEP 0
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    g_thingsmanager = new ThingsManager();
+    //**************************************************************
+
+    if (getuid() != 0)
+    {
+        std::cout << "NOTE: You may gain the root privilege (e.g, reboot)\n";
+        std::cout << "NOTE: Now, you don't have it.\n";
+    }
+
+    try
+    {
+        // Perform app tasks
+        while (true)
+        {
+
+            if (isWaiting > 0)
+                continue;
+
+            isWaiting = 0;
+
+            std::cout << endl << endl << "(0) Quit" << std::endl;
+            std::cout << "(1) Bootstrap" << std::endl;
+            std::cout << "(2) Create Configuration Resources" << std::endl;
+
+            cin >> g_Steps;
+            //
+            if (g_Steps == 0)
+                break;
+            else if (g_Steps == 1)
+            {
+                g_thingsmanager->doBootstrap(&onBootstrap);
+                isWaiting = 1;
+            }
+            else if (g_Steps == 2)
+            {
+                myConfigurationCollection = new ConfigurationCollection();
+                myConfigurationCollection->createResources(&entityHandlerForResource);
+
+                myDiagnosticsCollection = new DiagnosticsCollection();
+                myDiagnosticsCollection->createResources(&entityHandlerForResource);
+
+                myFactorySetCollection = new FactorySetCollection();
+                myFactorySetCollection->createResources(&entityHandlerForResource);
+                myDiagnosticsCollection->factoryReset = std::function < void()
+                        > (std::bind(&ConfigurationCollection::factoryReset,
+                                myConfigurationCollection));
+                isWaiting = 1;
+            }
+        }
+    }
+    catch (OCException e)
+    {
+        std::cout << "Exception in main: " << e.what();
+    }
+
+    // No explicit call to stop the platform.
+    // When OCPlatform destructor is invoked, internally we do platform cleanup
+}
+
diff --git a/service/things-manager/sampleapp/linux/configuration/makefile b/service/things-manager/sampleapp/linux/configuration/makefile
new file mode 100644 (file)
index 0000000..37824a9
--- /dev/null
@@ -0,0 +1,71 @@
+TGMROOT=../../../
+IOT_BASE=${TGMROOT}../../resource
+RST_NAME=.
+TARGET1=con-server
+TARGET2=con-client
+TARGET3=bootstrapserver
+
+OBJS = ConfigurationCollection.o DiagnosticsCollection.o FactorySetCollection.o con-server.o
+SRCS = $(OBJS:.o=.c)
+
+# C++ type Compile Flag define.
+CXX=g++
+CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
+
+CXX_INC        := -I../../ -I../../inc/ -I../../../sdk/inc/ -I../../../sdk/src/
+CXX_INC        += -I${IOT_BASE}/include/
+CXX_INC        += -I${IOT_BASE}/oc_logger/include
+CXX_INC        += -I${IOT_BASE}/csdk/stack/include
+CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include
+CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include
+CXX_INC        += -I${IOT_BASE}/csdk/logger/include
+CXX_INC        += -I${IOT_BASE}/dependencies/cereal/include
+
+CXX_LIB=-L""
+
+CXX_SRCPATH=${wildcard ../../src/*.cpp}
+CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
+CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
+CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
+
+
+TGM = ../../
+SDK = ${TGMROOT}sdk
+TGM_INC = -I${TGMROOT}sdk/inc
+SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
+
+LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
+
+LD_LIB := $(IOT_BASE)/release/obj/liboc.a
+LD_LIB += $(IOT_BASE)/csdk/linux/release/liboctbstack.a
+LD_LIB += $(LIB_OC_LOGGER)
+
+
+# Force metatargets to build:
+.PHONY: all clean
+
+all: ${TARGET1} ${TARGET2} ${TARGET3}
+
+.cpp.o:
+       $(CXX) $(CXX_FLAGS) -c -o $@ $<  $(CXX_INC)  $(TGM_INC)
+
+$(TARGET1): $(OBJS)
+       $(CXX) $(CXX_FLAGS) -o $@ ${OBJS} $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+${TARGET2}: con-client.cpp
+       $(CXX) $(CXX_FLAGS) -o ${TARGET2} $<  $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+${TARGET3}: bootstrapserver.cpp
+       $(CXX) $(CXX_FLAGS) -o ${TARGET3} $<  $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+
+dep:
+       gccmakedep $(SRCS)
+
+clean:
+       rm -f -v *.o con-client
+       rm -f -v *.o con-server
+       rm -f -v *.o bootstrapserver
+
+#dep:
+#      gccmakedep $(SRCS)
diff --git a/service/things-manager/sampleapp/linux/groupaction/SConscript b/service/things-manager/sampleapp/linux/groupaction/SConscript
new file mode 100644 (file)
index 0000000..1ed0695
--- /dev/null
@@ -0,0 +1,35 @@
+##
+# linux sample app  build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+linux_sample_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
+linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack', 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+
+
+######################################################################
+#build sampleapp
+######################################################################
+groupserver = linux_sample_env.Program('groupserver', 'groupserver.cpp')
+lightserver = linux_sample_env.Program('lightserver', 'lightserver.cpp')
+bookmark = linux_sample_env.Program('bookmark', 'bookmark.cpp')
+Alias("GroupServerApp", groupserver)
+Alias("LightServerApp", lightserver)
+Alias("BookmarkApp", bookmark)
+env.AppendTarget('GroupServerApp')
+env.AppendTarget('LightServerApp')
+env.AppendTarget('BookmarkApp')
diff --git a/service/things-manager/sampleapp/linux/groupaction/bookmark.cpp b/service/things-manager/sampleapp/linux/groupaction/bookmark.cpp
new file mode 100644 (file)
index 0000000..6f67aef
--- /dev/null
@@ -0,0 +1,235 @@
+//******************************************************************
+//
+// Copyright 2014 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 <functional>
+#include <pthread.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+
+namespace PH = std::placeholders;
+
+unsigned int startedThread;
+unsigned int gObservation;
+pthread_t threadId;
+
+void* ObserveHandler(void *param);
+
+class BookmarkResource
+{
+
+private:
+    OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
+    {
+        OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+        if (request)
+        {
+            // Get the request type and request flag
+            std::string requestType = request->getRequestType();
+            int requestFlag = request->getRequestHandlerFlag();
+
+            if (requestFlag & RequestHandlerFlag::InitFlag)
+            {
+                cout << "\t\trequestFlag : Init\n";
+
+                // entity handler to perform resource initialization operations
+            }
+            else if (requestFlag & RequestHandlerFlag::RequestFlag)
+            {
+                auto pResponse = std::make_shared< OC::OCResourceResponse >();
+                pResponse->setRequestHandle(request->getRequestHandle());
+                pResponse->setResourceHandle(request->getResourceHandle());
+
+                // If the request type is GET
+                if (requestType == "GET")
+                {
+                }
+                else if (requestType == "PUT")
+                {
+                    cout << "\t\t\trequestType : PUT\n";
+                }
+                else if (requestType == "POST")
+                {
+                    // POST request operations
+                }
+                else if (requestType == "DELETE")
+                {
+                    // DELETE request operations
+                }
+
+                pResponse->setErrorCode(200);
+                pResponse->setResponseResult(OC_EH_OK);
+                pResponse->setResourceRepresentation(getRepresentation());
+                if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                {
+                    ehResult = OC_EH_OK;
+                }
+            }
+
+            if (requestFlag & RequestHandlerFlag::ObserverFlag)
+            {
+                cout << "\t\trequestFlag : Observer\n";
+
+                if (!startedThread)
+                {
+                    pthread_create(&threadId, NULL, ObserveHandler, (void *) NULL);
+                    startedThread = 1;
+                    gObservation = 1;
+                }
+
+                ehResult = OC_EH_OK;
+            }
+        }
+        else
+        {
+            std::cout << "Request invalid" << std::endl;
+        }
+
+        return ehResult;
+    }
+
+public:
+    /// Constructor
+    BookmarkResource()
+    {
+        m_pressure = 0;
+
+        m_BookmarkUri = "/core/bookmark"; // URI of the resource
+        m_BookmarkType = "core.bookmark"; // resource type name. In this case, it is light
+
+        m_BookmarkInterface = DEFAULT_INTERFACE; // resource interface.
+        m_BookmarkHandle = 0;
+    }
+
+    /// This function internally calls registerResource API.
+    void createResources()
+    {
+        EntityHandler cb = std::bind(&BookmarkResource::entityHandler, this, PH::_1);
+
+        // This will internally create and register the resource.
+        OCStackResult result = OC::OCPlatform::registerResource(m_BookmarkHandle, m_BookmarkUri,
+                m_BookmarkType, m_BookmarkInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+        if (OC_STACK_OK != result)
+        {
+            cout << "Resource creation (bookmark) was unsuccessful\n";
+        }
+        else
+        {
+            cout << "Resource URI : " << m_BookmarkUri << endl;
+            cout << "\tResource Type Name : " << m_BookmarkType << endl;
+            cout << "\tResource Interface : " << DEFAULT_INTERFACE << endl;
+            cout << "\tResource creation is successful with resource handle : " << m_BookmarkHandle
+                    << endl;
+        }
+    }
+
+    void setRepresentation(OCRepresentation& rep)
+    {
+        // AttributeMap attributeMap = rep.getAttributeMap();
+        // if(rep.getValue("level", m_pressure) == true)
+        {
+            std::cout << m_pressure << endl;
+        }
+    }
+
+    OCRepresentation getRepresentation()
+    {
+        OCRepresentation rep;
+
+        rep.setValue("level", (int) m_pressure);
+
+        return rep;
+    }
+
+public:
+    // Members of Bookmark
+    std::string m_BookmarkUri;
+    std::string m_BookmarkType;
+    std::string m_BookmarkInterface;
+    unsigned int m_pressure;
+    OCResourceHandle m_BookmarkHandle;
+};
+
+// Create the instance of the resource class (in this case instance of class 'BookmarkResource').
+BookmarkResource myBookmarkResource;
+
+void* ObserveHandler(void *param)
+{
+    while (startedThread)
+    {
+        sleep(1);
+
+        cout << "input a integer(0:opened, 5:close) : ";
+        cin >> myBookmarkResource.m_pressure;
+
+        if (myBookmarkResource.m_pressure == 0 || // When your book opened.
+                myBookmarkResource.m_pressure == 5) // When your book closed.
+        {
+            cout << "notifyObservers call!" << endl;
+
+            OCStackResult result = OCPlatform::notifyAllObservers(
+                    myBookmarkResource.m_BookmarkHandle);
+
+            if (OC_STACK_NO_OBSERVERS == result)
+            {
+                cout << "No More observers, stopping notifications" << endl;
+                gObservation = 0;
+                startedThread = 0;
+            }
+        }
+    }
+
+    return NULL;
+}
+
+int main()
+{
+    // Create PlatformConfig object
+
+    OC::PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0",
+    // By setting to "0.0.0.0", it binds to all available interfaces
+            0,// Uses randomly available port
+            OC::QualityOfService::LowQos };
+
+    // Create a OCPlatform instance.
+    // Note: Platform creation is synchronous call.
+    try
+    {
+
+        // Invoke createResource function of class bookmark.
+        myBookmarkResource.createResources();
+
+        // Perform app tasks
+        while (true)
+        {
+            // some tasks
+        }
+    }
+    catch (OCException e)
+    {
+        std::cout << "Exception in main: " << e.what();
+    }
+}
diff --git a/service/things-manager/sampleapp/linux/groupaction/groupserver.cpp b/service/things-manager/sampleapp/linux/groupaction/groupserver.cpp
new file mode 100644 (file)
index 0000000..47177c7
--- /dev/null
@@ -0,0 +1,433 @@
+//******************************************************************
+//
+// Copyright 2014 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 <OCPlatform.h>
+#include <OCApi.h>
+
+#include <functional>
+#include <pthread.h>
+#include <iostream>
+
+#include <ThingsManager.h>
+
+using namespace std;
+using namespace OC;
+using namespace OIC;
+namespace PH = std::placeholders;
+
+bool isReady = false;
+
+OCResourceHandle resourceHandle;
+std::vector< OCResourceHandle > resourceHandleVector;
+
+shared_ptr< OCResource > g_resource;
+vector< string > lights;
+
+ThingsManager *thingsMgr = new ThingsManager();
+
+void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode);
+
+void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
+
+void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode);
+
+void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, const int& eCode,
+        const int& sequenceNumber);
+
+void allBulbOn();
+void allBulbOff();
+
+void foundResources(std::vector< std::shared_ptr< OC::OCResource > > listOfResource)
+{
+
+    for (auto rsrc = listOfResource.begin(); rsrc != listOfResource.end(); ++rsrc)
+    {
+        std::string resourceURI = (*rsrc)->uri();
+        std::string hostAddress = (*rsrc)->host();
+
+        if (resourceURI == "/a/light")
+        {
+
+            cout << "\tResource URI : " << resourceURI << endl;
+            cout << "\tResource Host : " << hostAddress << endl;
+
+            OCResourceHandle foundResourceHandle;
+            OCStackResult result = OCPlatform::registerResource(foundResourceHandle, (*rsrc));
+            cout << "\tresource registed!" << endl;
+            if (result == OC_STACK_OK)
+            {
+                OCPlatform::bindResource(resourceHandle, foundResourceHandle);
+                resourceHandleVector.push_back(foundResourceHandle);
+            }
+            else
+            {
+                cout << "\tresource Error!" << endl;
+            }
+
+            lights.push_back((hostAddress + resourceURI));
+        }
+    }
+
+    isReady = true;
+}
+
+void foundResource(std::shared_ptr< OCResource > resource)
+{
+    std::string resourceURI;
+    std::string hostAddress;
+
+    try
+    {
+        cout << "FOUND RESOURCE" << endl;
+
+        if (resource)
+        {
+            resourceURI = resource->uri();
+            hostAddress = resource->host();
+            if (resourceURI == "/core/a/collection")
+            {
+                g_resource = resource;
+
+                // g_resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet);
+
+                printf("\tHOST :: %s\n", resource->host().c_str());
+            }
+            else if (resourceURI == "/core/bookmark")
+            {
+                resource->observe(ObserveType::Observe, QueryParamsMap(), &onObserve);
+            }
+
+            // p_platform.bindResource(resourceHandle, foundResourceHandle);
+
+        }
+    }
+    catch (std::exception& e)
+    {
+        std::cout << "" << std::endl;
+    }
+}
+
+void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode)
+{
+    // std::vector<OCRepresentation> children = rep.getChildren();
+
+    // cout << "\n\n\nCHILD RESOURCE OF GROUP" << endl;
+    // for( auto iter = children.begin(); iter != children.end();  ++iter )
+    // {
+    //     lights.push_back((*iter).getUri());
+    //     cout << "\tURI :: " << (*iter).getUri() << endl;
+    // }
+}
+
+void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    printf("\nonPut\n");
+}
+
+void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    printf("\nonPost\n");
+
+    if (rep.hasAttribute("ActionSet"))
+    {
+        std::string plainText;
+
+        if (rep.getValue("ActionSet", plainText))
+        {
+            ActionSet *actionset = thingsMgr->getActionSetfromString(plainText);
+            if (actionset != NULL)
+            {
+                cout << endl << "\tACTIONSET NAME :: " << actionset->actionsetName << endl;
+                for (auto actIter = actionset->listOfAction.begin();
+                        actIter != actionset->listOfAction.end(); ++actIter)
+                {
+                    cout << "\t\tTARGET :: " << (*actIter)->target << endl;
+
+                    for (auto capaIter = (*actIter)->listOfCapability.begin();
+                            capaIter != (*actIter)->listOfCapability.end(); ++capaIter)
+                    {
+                        cout << "\t\t\t" << (*capaIter)->capability << " :: " << (*capaIter)->status
+                                << endl;
+                    }
+                }
+            }
+            delete actionset;
+        }
+
+        // printf( "\tPlain Text :: %s\n", plainText.c_str() );
+    }
+    else if (rep.hasAttribute("DoAction"))
+    {
+        std::string plainText;
+        if (rep.getValue("DoAction", plainText))
+        {
+            cout << "\t" << plainText << endl;
+        }
+    }
+    else
+    {
+
+    }
+}
+
+void allBulbOff()
+{
+    OCRepresentation rep;
+
+    rep.setValue("DoAction", std::string("AllBulbOff"));
+
+    if (g_resource)
+    {
+        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), &onPost);
+    }
+}
+
+void allBulbOn()
+{
+    OCRepresentation rep;
+
+    rep.setValue("DoAction", std::string("AllBulbOn"));
+
+    if (g_resource)
+    {
+        g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), &onPost);
+    }
+}
+
+void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, const int& eCode,
+        const int& sequenceNumber)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        int level;
+
+        std::cout << "OBSERVE RESULT:" << std::endl;
+        std::cout << "\tSequenceNumber: " << sequenceNumber << endl;
+
+        if (rep.getValue("level", level))
+        {
+            if (level == 0)
+            {
+                allBulbOn();
+            }
+            else
+            {
+                allBulbOff();
+            }
+        }
+        std::cout << "\tlevel: " << level << std::endl;
+    }
+    else
+    {
+        std::cout << "onObserve Response error: " << eCode << std::endl;
+        std::exit(-1);
+    }
+}
+
+void createActionSet_AllBulbOff()
+{
+    string actionsetDesc;
+    ActionSet *allBulbOff = new ActionSet();
+    allBulbOff->actionsetName = "AllBulbOff";
+
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        Action *action = new Action();
+        action->target = (*iter);
+
+        Capability *capa = new Capability();
+        capa->capability = "power";
+        capa->status = "off";
+
+        action->listOfCapability.push_back(capa);
+        allBulbOff->listOfAction.push_back(action);
+    }
+    // actionsetDesc = thingsMgr->getStringFromActionSet(allBulbOff);
+
+    // cout << "ActionSet :: " << actionsetDesc << endl;
+
+    // OCRepresentation rep;
+    // rep.setValue("ActionSet", actionsetDesc);
+
+    if (g_resource)
+    {
+        thingsMgr->addActionSet(g_resource, allBulbOff, onPut);
+        // g_resource->put("a.collection", GROUP_INTERFACE, rep,
+        //     QueryParamsMap(), &onPut);
+    }
+
+    delete allBulbOff;
+}
+
+void createActionSet_AllBulbOn()
+{
+    string actionsetDesc;
+    ActionSet *allBulbOff = new ActionSet();
+    allBulbOff->actionsetName = "AllBulbOn";
+
+    for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+    {
+        Action *action = new Action();
+        action->target = (*iter);
+
+        Capability *capa = new Capability();
+        capa->capability = "power";
+        capa->status = "on";
+
+        action->listOfCapability.push_back(capa);
+        allBulbOff->listOfAction.push_back(action);
+    }
+    // actionsetDesc = thingsMgr->getStringFromActionSet(allBulbOff);
+
+    // cout << "ActionSet :: " << actionsetDesc << endl;
+
+    // OCRepresentation rep;
+    // rep.setValue("ActionSet", actionsetDesc);
+
+    if (g_resource)
+    {
+        thingsMgr->addActionSet(g_resource, allBulbOff, onPut);
+        // g_resource->put("a.collection", GROUP_INTERFACE, rep,
+        //     QueryParamsMap(), &onPut);
+    }
+
+    delete allBulbOff;
+}
+
+int main()
+{
+    PlatformConfig config
+    { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    try
+    {
+        string resourceURI = "/core/a/collection";
+        string resourceTypeName = "a.collection";
+        string resourceInterface = BATCH_INTERFACE;
+        OCPlatform::Configure(config);
+
+        // Find lights for group creation.
+        vector< string > types;
+        types.push_back("core.light");
+        thingsMgr->findCandidateResources(types, &foundResources, 5);
+
+        OCPlatform::registerResource(resourceHandle, resourceURI, resourceTypeName,
+                resourceInterface, NULL,
+                //&entityHandler, // entityHandler
+                OC_DISCOVERABLE);
+
+        cout << "registerResource is called." << endl;
+
+        OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
+        OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
+
+        bool isRun = true;
+
+        while (isRun)
+        {
+            while (isReady)
+            {
+                int n;
+
+                cout << endl;
+                cout << "1 :: CREATE ACTIONSET 2 :: EXECUTE ACTIONSET(ALLBULBON)"
+                        << "3 :: EXECUTE ACTIONSET(ALLBULBOFF)" << endl;
+                cout << "4 :: GET ACTIONSET 5 :: DELETE ACTIONSET 6 :: QUIT" << endl;
+                cout << "9 :: FIND GROUP 0 :: FIND BOOKMARK TO OBSERVE" << endl;
+
+                fflush(stdin);
+                cin >> n;
+
+                if (n == 9)
+                {
+                    OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=a.collection",
+                            &foundResource);
+                }
+                else if (n == 0)
+                {
+                    OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.bookmark",
+                            &foundResource);
+                }
+                else if (n == 1)
+                {
+
+                    // Craete Action Set
+                    // "AllBulbOff"
+                    //"movieTime*uri=coap://10.251.44.228:49858/a/light|power=10";
+                    createActionSet_AllBulbOff();
+                    createActionSet_AllBulbOn();
+
+                }
+                else if (n == 2)
+                {
+
+                    allBulbOn();
+                    // thingsMgr->executeActionSet(g_resource, "AllBulbOn", onPost);
+
+                }
+                else if (n == 3)
+                {
+
+                    allBulbOff();
+                    // thingsMgr->executeActionSet(g_resource, "AllBulbOff", onPost);
+
+                }
+                else if (n == 4)
+                {
+                    // OCRepresentation rep;
+
+                    // rep.setValue("GetActionSet", std::string("AllBulbOff"));
+
+                    // if(g_resource)
+                    // {
+                    //     g_resource->post("a.collection", GROUP_INTERFACE, rep,
+                    //         QueryParamsMap(), &onPost);
+                    // }
+
+                    thingsMgr->getActionSet(g_resource, "AllBulbOff", onPost);
+                }
+                else if (n == 5)
+                {
+                    // OCRepresentation rep;
+
+                    // rep.setValue("DelActionSet", std::string("AllBulbOff"));
+
+                    // if(g_resource)
+                    // {
+                    //     g_resource->put("a.collection", GROUP_INTERFACE, rep,
+                    //         QueryParamsMap(), &onPut);
+                    // }
+                    thingsMgr->deleteActionSet(g_resource, "AllBulbOff", onPut);
+                }
+                else if (n == 6)
+                {
+                    isRun = false;
+                    break;
+                }
+            }
+        }
+    }
+    catch (OCException& e)
+    {
+
+    }
+
+    return 0;
+}
diff --git a/service/things-manager/sampleapp/linux/groupaction/lightserver.cpp b/service/things-manager/sampleapp/linux/groupaction/lightserver.cpp
new file mode 100644 (file)
index 0000000..d73bf5e
--- /dev/null
@@ -0,0 +1,337 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// This sample provides steps to define an interface for a resource
+/// (properties and methods) and host this resource on the server.
+///
+
+#include <functional>
+
+#include <pthread.h>
+#include <mutex>
+#include <condition_variable>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int gObservation = 0;
+void * ChangeLightRepresentation(void *param);
+void * handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest);
+
+// Specifies secure or non-secure
+// false: non-secure resource
+// true: secure resource
+bool isSecure = false;
+
+/// Specifies whether Entity handler is going to do slow response or not
+bool isSlowResponse = false;
+
+// Forward declaring the entityHandler
+
+/// This class represents a single resource named 'lightResource'. This resource has
+/// two simple properties named 'state' and 'power'
+
+class LightResource
+{
+
+public:
+    /// Access this property from a TB client
+    std::string m_power;
+    std::string m_lightUri;
+    OCResourceHandle m_resourceHandle;
+    OCRepresentation m_lightRep;
+
+public:
+    /// Constructor
+    LightResource() :
+            m_power(""), m_lightUri("/a/light"), m_resourceHandle(0)
+    {
+        // Initialize representation
+        m_lightRep.setUri(m_lightUri);
+
+        m_lightRep.setValue("power", m_power);
+    }
+
+    /* Note that this does not need to be a member function: for classes you do not have
+     access to, you can accomplish this with a free function: */
+
+    /// This function internally calls registerResource API.
+    void createResource()
+    {
+        std::string resourceURI = m_lightUri; //URI of the resource
+        std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
+        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+
+        EntityHandler cb = std::bind(&LightResource::entityHandler, this, PH::_1);
+
+        // This will internally create and register the resource.
+        OCStackResult result = OCPlatform::registerResource(m_resourceHandle, resourceURI,
+                resourceTypeName, resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+        if (OC_STACK_OK != result)
+        {
+            cout << "Resource creation was unsuccessful\n";
+        }
+        else
+        {
+            cout << "Resource URI : " << resourceURI << endl;
+            cout << "\tResource Type Name : " << resourceTypeName << endl;
+            cout << "\tResource Interface : " << DEFAULT_INTERFACE << endl;
+            cout << "\tResource creation is successful with resource handle : " << m_resourceHandle
+                    << endl;
+        }
+    }
+
+    OCResourceHandle getHandle()
+    {
+        return m_resourceHandle;
+    }
+
+    // Puts representation.
+    // Gets values from the representation and
+    // updates the internal state
+    void put(OCRepresentation& rep)
+    {
+        try
+        {
+            if (rep.getValue("power", m_power))
+            {
+                cout << "\t\t\t\t" << "power: " << m_power << endl;
+            }
+            else
+            {
+                cout << "\t\t\t\t" << "power not found in the representation" << endl;
+            }
+        }
+        catch (exception& e)
+        {
+            cout << e.what() << endl;
+        }
+
+    }
+
+    // Post representation.
+    // Post can create new resource or simply act like put.
+    // Gets values from the representation and
+    // updates the internal state
+    OCRepresentation post(OCRepresentation& rep)
+    {
+        put(rep);
+        return get();
+    }
+
+    // gets the updated representation.
+    // Updates the representation with latest internal state before
+    // sending out.
+    OCRepresentation get()
+    {
+        m_lightRep.setValue("power", m_power);
+
+        return m_lightRep;
+    }
+
+    void addType(const std::string& type) const
+    {
+        OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+    void addInterface(const std::string& interface) const
+    {
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        if (OC_STACK_OK != result)
+        {
+            cout << "Binding TypeName to Resource was unsuccessful\n";
+        }
+    }
+
+private:
+// This is just a sample implementation of entity handler.
+// Entity handler can be implemented in several ways by the manufacturer
+    OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
+    {
+        cout << "\tIn Server CPP entity handler:\n";
+        OCEntityHandlerResult ehResult = OC_EH_ERROR;
+        if (request)
+        {
+            // Get the request type and request flag
+            std::string requestType = request->getRequestType();
+            int requestFlag = request->getRequestHandlerFlag();
+
+            if (requestFlag & RequestHandlerFlag::InitFlag)
+            {
+                cout << "\t\trequestFlag : Init\n";
+
+                // entity handler to perform resource initialization operations
+            }
+            if (requestFlag & RequestHandlerFlag::RequestFlag)
+            {
+                cout << "\t\trequestFlag : Request\n";
+                auto pResponse = std::make_shared< OC::OCResourceResponse >();
+                pResponse->setRequestHandle(request->getRequestHandle());
+                pResponse->setResourceHandle(request->getResourceHandle());
+
+                // If the request type is GET
+                if (requestType == "GET")
+                {
+                    cout << "\t\t\trequestType : GET\n";
+                    if (isSlowResponse) // Slow response case
+                    {
+                        static int startedThread = 0;
+                        if (!startedThread)
+                        {
+                            std::thread t(handleSlowResponse, (void *) this, request);
+                            startedThread = 1;
+                            t.detach();
+                        }
+                        ehResult = OC_EH_SLOW;
+                    }
+                    else // normal response case.
+                    {
+                        pResponse->setErrorCode(200);
+                        pResponse->setResponseResult(OC_EH_OK);
+                        pResponse->setResourceRepresentation(get());
+                        if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                        {
+                            ehResult = OC_EH_OK;
+                        }
+                    }
+                }
+                else if (requestType == "PUT")
+                {
+                    cout << "\t\t\trequestType : PUT\n";
+                    OCRepresentation rep = request->getResourceRepresentation();
+
+                    // Do related operations related to PUT request
+                    // Update the lightResource
+                    put(rep);
+                    pResponse->setErrorCode(200);
+                    pResponse->setResponseResult(OC_EH_OK);
+                    pResponse->setResourceRepresentation(get());
+                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        ehResult = OC_EH_OK;
+                    }
+                }
+                else if (requestType == "POST")
+                {
+                    cout << "\t\t\trequestType : POST\n";
+
+                    OCRepresentation rep = request->getResourceRepresentation();
+
+                    // Do related operations related to POST request
+                    OCRepresentation rep_post = post(rep);
+                    pResponse->setResourceRepresentation(rep_post);
+                    pResponse->setErrorCode(200);
+                    if (rep_post.hasAttribute("createduri"))
+                    {
+                        pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+                        pResponse->setNewResourceUri(
+                                rep_post.getValue< std::string >("createduri"));
+                    }
+
+                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        ehResult = OC_EH_OK;
+                    }
+                }
+                else if (requestType == "DELETE")
+                {
+                    // DELETE request operations
+                }
+            }
+        }
+        else
+        {
+            std::cout << "Request invalid" << std::endl;
+        }
+
+        return ehResult;
+    }
+};
+
+void * handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest)
+{
+    // This function handles slow response case
+    LightResource* lightPtr = (LightResource*) param;
+    // Induce a case for slow response by using sleep
+    std::cout << "SLOW response" << std::endl;
+    sleep(10);
+
+    auto pResponse = std::make_shared< OC::OCResourceResponse >();
+    pResponse->setRequestHandle(pRequest->getRequestHandle());
+    pResponse->setResourceHandle(pRequest->getResourceHandle());
+    pResponse->setResourceRepresentation(lightPtr->get());
+    pResponse->setErrorCode(200);
+    pResponse->setResponseResult(OC_EH_OK);
+
+    // Set the slow response flag back to false
+    isSlowResponse = false;
+    OCPlatform::sendResponse(pResponse);
+    return NULL;
+}
+
+int main(int argc, char* argv[])
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0",
+    // By setting to "0.0.0.0", it binds to all available interfaces
+            0,// Uses randomly available port
+            OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    try
+    {
+        // Create the instance of the resource class
+        // (in this case instance of class 'LightResource').
+        LightResource myLight;
+
+        // Invoke createResource function of class light.
+        myLight.createResource();
+
+        // A condition variable will free the mutex it is given, then do a non-
+        // intensive block until 'notify' is called on it.  In this case, since we
+        // don't ever call cv.notify, this should be a non-processor intensive version
+        // of while(true);
+        std::mutex blocker;
+        std::condition_variable cv;
+        std::unique_lock < std::mutex > lock(blocker);
+        cv.wait(lock);
+    }
+    catch (OCException e)
+    {
+        //log(e.what());
+    }
+
+    // No explicit call to stop the platform.
+    // When OCPlatform::destructor is invoked, internally we do platform cleanup
+
+    return 0;
+}
diff --git a/service/things-manager/sampleapp/linux/groupaction/makefile b/service/things-manager/sampleapp/linux/groupaction/makefile
new file mode 100644 (file)
index 0000000..6604c3c
--- /dev/null
@@ -0,0 +1,70 @@
+
+TGMROOT=../../../
+IOT_BASE=${TGMROOT}../../resource
+RST_NAME=.
+
+
+
+# C++ type Compile Flag define.
+CXX=g++
+CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
+
+DEPEND_DIR:= ../../../../../resource/dependencies/
+CEREAL_DIR:= $(DEPEND_DIR)/cereal
+
+CXX_INC        := -I../../ -I../../inc/
+CXX_INC        += -I${IOT_BASE}/include/
+CXX_INC        += -I${IOT_BASE}/oc_logger/include
+CXX_INC        += -I${IOT_BASE}/csdk/stack/include
+CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include
+CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include
+CXX_INC        += -I${IOT_BASE}/csdk/logger/include
+CXX_INC        += -I$(CEREAL_DIR)/include
+CXX_INC        += -I../../../sdk/inc
+CXX_INC        += -I../../../sdk/src
+
+
+CXX_LIB=-L""
+
+CXX_SRCPATH=${wildcard ../../src/*.cpp}
+CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
+CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
+CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
+
+
+TGM = ../../
+SDK = ${TGMROOT}sdk
+TGM_INC = -I${TGMROOT}sdk/inc
+SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
+
+LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
+
+LD_LIB := $(IOT_BASE)/release/obj/liboc.a
+LD_LIB += $(IOT_BASE)/csdk/linux/release/liboctbstack.a
+LD_LIB += $(LIB_OC_LOGGER)
+
+
+# Force metatargets to build:
+.PHONY: all clean
+
+all: bookmark lightserver groupserver
+
+#groupclient
+bookmark: ./bookmark.cpp
+       $(CXX) $(CXX_FLAGS) -o bookmark ./bookmark.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+lightserver: ./lightserver.cpp
+       $(CXX) $(CXX_FLAGS) -o lightserver ./lightserver.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+groupserver: ./groupserver.cpp
+       $(CXX) $(CXX_FLAGS) -o groupserver ./groupserver.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+# groupclient: ./groupclient.cpp
+#      $(CXX) $(CXX_FLAGS) -o groupclient ./groupclient.cpp $(CXX_INC) ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+clean:
+       rm -f -v *.o ${TARGET}
+       rm -f groupserver
+       rm -f groupclient
+       rm -f lightserver
+       rm -f bookmark
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/SConscript b/service/things-manager/sampleapp/linux/groupsyncaction/SConscript
new file mode 100644 (file)
index 0000000..25d9b49
--- /dev/null
@@ -0,0 +1,38 @@
+##
+# linux sample app  build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+linux_sample_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+linux_sample_env.AppendUnique(CPPPATH = ['include'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
+linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/src'])
+linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
+linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
+linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack', 'libcoap', 'liboc_logger', 'dl', 'pthread'])
+
+
+######################################################################
+#build sampleapp
+######################################################################
+group = linux_sample_env.Program('group', 'group.cpp')
+musicplayer = linux_sample_env.Program('musicplayer', 'musicplayer.cpp')
+phone = linux_sample_env.Program('phone', 'phone.cpp')
+speaker = linux_sample_env.Program('speaker', 'speaker.cpp')
+Alias("GroupApp", group)
+Alias("ConCleintApp", musicplayer)
+Alias("PhoneApp", phone)
+Alias("SpeakerApp", speaker)
+env.AppendTarget('GroupApp')
+env.AppendTarget('MusicplayerApp')
+env.AppendTarget('PhoneApp')
+env.AppendTarget('SpeakerApp')
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/group.cpp b/service/things-manager/sampleapp/linux/groupsyncaction/group.cpp
new file mode 100644 (file)
index 0000000..d8b1082
--- /dev/null
@@ -0,0 +1,223 @@
+//******************************************************************
+//
+// Copyright 2014 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 <string>
+#include <cstdlib>
+#include <pthread.h>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+using namespace OIC;
+
+static ThingsManager* gThingManager = NULL;
+
+static std::vector< OCResourceHandle > gResourceHandleList;
+
+static std::string collectionResourceType = "core.group";
+
+void onFindResource(std::shared_ptr< OCResource > resource)
+{
+    cout << "onFindResource" << endl;
+
+    if (resource)
+    {
+        OCResourceHandle resourceHandle;
+        OCStackResult result = OCPlatform::registerResource(resourceHandle, resource);
+        if (OC_STACK_OK == result)
+        {
+            cout << "onFindResource : Resource creation was successful\n";
+        }
+        else
+        {
+            cout << "onFindResource : Resource creation was unsuccessful\n";
+            return;
+        }
+
+        result = gThingManager->joinGroup(collectionResourceType, resourceHandle);
+        if (OC_STACK_OK == result)
+        {
+            cout << "onFindResource : Joining group was successful\n";
+        }
+        else
+        {
+            cout << "onFindResource : Joining group was unsuccessful\n";
+
+            OCPlatform::unregisterResource(resourceHandle);
+            return;
+        }
+
+        gResourceHandleList.push_back(resourceHandle);
+    }
+    else
+    {
+        cout << "onFindResource : There is no found resource." << endl;
+    }
+}
+
+int main(int argc, char* argv[])
+{
+
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Both/*OC::ModeType::Server*/, "0.0.0.0", 0,
+            OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    gThingManager = new ThingsManager();
+
+    int selectedMenu;
+    OCStackResult result;
+
+    try
+    {
+        while (true)
+        {
+            // some operations
+            cout << "(1) CREATE GROUP " << endl;
+            cout << "(11) FIND MUSIC PLAYER & JOIN GROUP | (12) FIND SPEAKER & JOIN GROUP" << endl;
+            cout << "(21) LEAVE GROUP - MUSIC PLAYER  | (22) LEAVE GROUP - SPEAKER" << endl;
+            cout << "(31) DELETE GROUP " << endl;
+
+            std::cin >> selectedMenu;
+
+            if (selectedMenu == 1)
+            {
+                result = gThingManager->createGroup(collectionResourceType);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Group creation was successful\n";
+                }
+                else
+                {
+                    cout << "Group creation was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 11)
+            {
+                result = OCPlatform::findResource("",
+                        "coap://224.0.1.187/oc/core?rt=core.musicplayer", onFindResource);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Finding music player was successful\n";
+                }
+                else
+                {
+                    cout << "Finding music player was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 12)
+            {
+                result = OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.speaker",
+                        onFindResource);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Finding speaker was successful\n";
+                }
+                else
+                {
+                    cout << "Finding speaker was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 21)
+            {
+                std::vector< OCResourceHandle >::iterator It;
+                OCResourceHandle resourceHandle;
+                for (It = gResourceHandleList.begin(); It != gResourceHandleList.end(); ++It)
+                {
+                    resourceHandle = (*It);
+                    std::string mpType = "core.musicplayer";
+                    std::string type = OCGetResourceTypeName(resourceHandle, 0);
+                    if (0 == mpType.compare(type))
+                    {
+                        result = gThingManager->leaveGroup(collectionResourceType, resourceHandle);
+                        if (OC_STACK_OK == result)
+                        {
+                            cout << "Leaving group of music player was successful\n";
+                        }
+                        else
+                        {
+                            cout << "Leaving group of music player was unsuccessful\n";
+                        }
+                        break;
+                    }
+                }
+
+                gResourceHandleList.erase(It);
+                result = OCPlatform::unregisterResource(resourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Unregistering music player was successful\n";
+                }
+                else
+                {
+                    cout << "Unregistering music player was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 22)
+            {
+                std::vector< OCResourceHandle >::iterator It;
+                OCResourceHandle resourceHandle;
+                for (It = gResourceHandleList.begin(); It != gResourceHandleList.end(); ++It)
+                {
+                    resourceHandle = (*It);
+                    std::string mpType = "core.speaker";
+                    std::string type = OCGetResourceTypeName(resourceHandle, 0);
+                    if (0 == mpType.compare(type))
+                    {
+                        result = gThingManager->leaveGroup(collectionResourceType, resourceHandle);
+                        if (OC_STACK_OK == result)
+                        {
+                            cout << "Leaving group of speaker was successful\n";
+                        }
+                        else
+                        {
+                            cout << "Leaving group of speaker was unsuccessful\n";
+                        }
+                        break;
+                    }
+                }
+
+                gResourceHandleList.erase(It);
+                result = OCPlatform::unregisterResource(resourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Unregistering speaker was successful\n";
+                }
+                else
+                {
+                    cout << "Unregistering speaker was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 31)
+            {
+                gThingManager->deleteGroup(collectionResourceType);
+            }
+        }
+    }
+    catch (OCException& e)
+    {
+        //log(e.what());
+    }
+
+    return 0;
+}
+
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/makefile b/service/things-manager/sampleapp/linux/groupsyncaction/makefile
new file mode 100644 (file)
index 0000000..0ee1e5c
--- /dev/null
@@ -0,0 +1,65 @@
+
+TGMROOT=../../../
+IOT_BASE=${TGMROOT}../../resource
+RST_NAME=.
+TARGET1=group
+TARGET2=phone
+TARGET3=musicplayer
+TARGET4=speaker
+BUILD:=release
+
+# C++ type Compile Flag define.
+CXX=g++
+CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
+
+CXX_INC        := -I../../ -I../../inc/ -I../../../sdk/inc/ -I../../../sdk/src/
+CXX_INC        += -I${IOT_BASE}/include/
+CXX_INC += -I${IOT_BASE}/oc_logger/include
+CXX_INC        += -I${IOT_BASE}/csdk/stack/include
+CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include
+CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include
+CXX_INC        += -I${IOT_BASE}/csdk/logger/include
+CXX_INC        += -I${IOT_BASE}/dependencies/cereal/include
+
+CXX_LIB=-L""
+
+CXX_SRCPATH=${wildcard ../../src/*.cpp}
+CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
+CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
+CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
+
+
+TGM = ../../
+SDK = ${TGMROOT}sdk
+TGM_INC = -I${TGMROOT}sdk/inc
+SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
+
+LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
+
+LD_LIB := $(IOT_BASE)/$(BUILD)/obj/liboc.a
+LD_LIB += $(IOT_BASE)/csdk/linux/$(BUILD)/liboctbstack.a
+LD_LIB += $(LIB_OC_LOGGER)
+
+
+# Force metatargets to build:
+.PHONY: all clean
+
+all: ${TARGET1} ${TARGET2} ${TARGET3} ${TARGET4}
+
+${TARGET1}: ./group.cpp
+       $(CXX) $(CXX_FLAGS) -o ${TARGET1} ./group.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+${TARGET2}: ./phone.cpp
+       $(CXX) $(CXX_FLAGS) -o ${TARGET2} ./phone.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+${TARGET3}: ./musicplayer.cpp
+       $(CXX) $(CXX_FLAGS) -o ${TARGET3} ./musicplayer.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+${TARGET4}: ./speaker.cpp
+       $(CXX) $(CXX_FLAGS) -o ${TARGET4} ./speaker.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
+
+clean:
+       rm -f -v *.o ${TARGET1}
+       rm -f -v *.o ${TARGET2}
+       rm -f -v *.o ${TARGET3}
+       rm -f -v *.o ${TARGET4}
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/musicplayer.cpp b/service/things-manager/sampleapp/linux/groupsyncaction/musicplayer.cpp
new file mode 100644 (file)
index 0000000..9a898a3
--- /dev/null
@@ -0,0 +1,163 @@
+//******************************************************************
+//
+// Copyright 2014 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 <string>
+#include <cstdlib>
+#include <pthread.h>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+
+OCEntityHandlerResult mpEntityHandler(const std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "mpEntityHandler:\n";
+
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+        std::string action;
+
+        if (requestFlag == RequestHandlerFlag::InitFlag)
+        {
+            cout << "\trequestFlag : Init\n";
+
+            // entity handler to perform resource initialization operations
+        }
+        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\trequestFlag : Request\n";
+
+            OCRepresentation rp = request->getResourceRepresentation();
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                cout << "\t\trequestType : GET\n";
+            }
+            else if (requestType == "PUT")
+            {
+                cout << "\t\trequestType : PUT\n";
+
+                action = rp.getValue< std::string >("play");
+                cout << "\t\t\tplay : " << action << endl;
+            }
+            else if (requestType == "POST")
+            {
+                cout << "\t\trequestType : POST\n";
+            }
+            else if (requestType == "DELETE")
+            {
+                cout << "\t\trequestType : DELETE\n";
+            }
+        }
+        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        {
+            cout << "\trequestFlag : Observer\n";
+        }
+    }
+    else
+    {
+        cout << "Request invalid" << endl;
+    }
+
+    return OC_EH_OK;
+}
+
+int main(int argc, char* argv[])
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+
+    int selectedMenu;
+    OCStackResult result;
+    OCResourceHandle mpResourceHandle = NULL;
+
+    try
+    {
+        while (true)
+        {
+            // some operations
+            cout << "(1) CREATE MUSIC PLAYER | (2) DELETE MUSIC PLAYER" << endl;
+
+            std::cin >> selectedMenu;
+
+            if (selectedMenu == 1)
+            {
+                if (mpResourceHandle)
+                {
+                    cout << "Music player resource is registered already." << endl;
+                    continue;
+                }
+
+                std::string resourceURi = "/core/musicplayer";
+                std::string resourceTypeName = "core.musicplayer";
+                std::string resourceInterface = DEFAULT_INTERFACE;
+
+                result = OCPlatform::registerResource(mpResourceHandle, resourceURi,
+                        resourceTypeName, resourceInterface, mpEntityHandler,
+                        OC_DISCOVERABLE | OC_OBSERVABLE);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "To register music player resource was successful\n";
+                }
+                else
+                {
+                    cout << "To register music player resource was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 2)
+            {
+                if (NULL == mpResourceHandle)
+                {
+                    cout
+                            << "Error! No resource to unregister. Register resource first!"
+                            << endl;
+                    continue;
+                }
+
+                result = OCPlatform::unregisterResource(mpResourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "To unregister music player resource was successful\n";
+                }
+                else
+                {
+                    cout << "To unregister music player resource was unsuccessful\n";
+                }
+
+                mpResourceHandle = NULL;
+            }
+        }
+    }
+    catch (OCException& e)
+    {
+        //log(e.what());
+    }
+
+    return 0;
+}
+
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/phone.cpp b/service/things-manager/sampleapp/linux/groupsyncaction/phone.cpp
new file mode 100644 (file)
index 0000000..57494d0
--- /dev/null
@@ -0,0 +1,478 @@
+//******************************************************************
+//
+// Copyright 2014 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 <string>
+#include <cstdlib>
+#include <pthread.h>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+using namespace OIC;
+
+static ThingsManager* gThingManager = NULL;
+
+static OCResourceHandle gPhoneResourceHandle = NULL;
+
+static std::shared_ptr< OCResource > gFindGroup = NULL;
+
+static std::string collectionResourceType = "core.group";
+
+static ActionSet* gPlayStart;
+
+static ActionSet* gPlayStop;
+
+void onFindGroup(std::shared_ptr< OCResource > resource)
+{
+    if (resource)
+    {
+        if (NULL == gPhoneResourceHandle)
+        {
+            cout
+                    << "onFindGroup : Error! No resource to join group. Register resource first!"
+                    << endl;
+            return;
+        }
+
+        if (gFindGroup)
+        {
+            cout << "onFindGroup : Found group is already saved." << endl;
+        }
+        else
+        {
+            cout << "onFindGroup : Found group is saved now." << endl;
+            gFindGroup = resource;
+        }
+
+        gThingManager->joinGroup(gFindGroup, gPhoneResourceHandle);
+    }
+    else
+    {
+        cout << "onFindGroup : Resource is invalid. So a new Group Resource has to be created."
+                << endl;
+    }
+}
+
+void onAction(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        cout << "onAction" << endl;
+    }
+    else
+    {
+        cout << "onAction : error - " << eCode << endl;
+    }
+}
+
+void onGetChild(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        gPlayStart = new ActionSet();
+        gPlayStop = new ActionSet();
+
+        gPlayStart->actionsetName = "playstart";
+        gPlayStop->actionsetName = "playstop";
+
+        std::vector< OCRepresentation > childList = rep.getChildren();
+        OCRepresentation child;
+        std::string resourceURI;
+
+        QueryParamsMap query;
+        OCRepresentation rep;
+        std::string playStart;
+        std::string playStop;
+
+        std::vector< std::string > types;
+        std::string resType;
+
+        OCStackResult result;
+
+        for (unsigned int i = 0; i < childList.size(); ++i)
+        {
+//            cout << "\n\tchild resource - " << i + 1 << endl;
+
+            child = childList.at(i);
+            resourceURI = child.getUri();
+
+//            cout << "\t\tURI of the resource: " << resourceURI << endl;
+
+//            cout << "\t\tList of resource types: " << endl;
+
+            types = child.getResourceTypes();
+
+            for (unsigned int j = 0; j < types.size(); ++j)
+            {
+                resType = types.at(j);
+//                cout << "\t\t\t" << resType << endl;
+
+                if (std::string::npos != resType.find("musicplayer"))
+                {
+                    Capability *pStartCapa = new Capability;
+                    pStartCapa->capability = "play";
+                    pStartCapa->status = "on";
+
+                    Action* pPlayStart = new Action();
+                    pPlayStart->target = resourceURI;
+                    pPlayStart->listOfCapability.push_back(pStartCapa);
+
+                    gPlayStart->listOfAction.push_back(pPlayStart);
+
+                    Capability *pStopCapa = new Capability;
+                    pStopCapa->capability = "play";
+                    pStopCapa->status = "off";
+
+                    Action* pPlayStop = new Action();
+                    pPlayStop->target = resourceURI;
+                    pPlayStop->listOfCapability.push_back(pStopCapa);
+
+                    gPlayStop->listOfAction.push_back(pPlayStop);
+                }
+                else if (std::string::npos != resType.find("speaker"))
+                {
+                    Capability *pStartCapa = new Capability;
+                    pStartCapa->capability = "volume";
+                    pStartCapa->status = "50";
+
+                    Action* pPlayStart = new Action();
+                    pPlayStart->target = resourceURI;
+                    pPlayStart->listOfCapability.push_back(pStartCapa);
+
+                    gPlayStart->listOfAction.push_back(pPlayStart);
+
+                    Capability *pStopCapa = new Capability;
+                    pStopCapa->capability = "volume";
+                    pStopCapa->status = "0";
+
+                    Action* pPlayStop = new Action();
+                    pPlayStop->target = resourceURI;
+                    pPlayStop->listOfCapability.push_back(pStopCapa);
+
+                    gPlayStop->listOfAction.push_back(pPlayStop);
+                }
+            }
+        }
+
+//        std::string temp = gThingManager->getStringFromActionSet (gPlayStart);
+//        cout << "play start - " << temp << endl;
+
+//        temp  = gThingManager->getStringFromActionSet (gPlayStop);
+//        cout << "play stop - " << temp << endl;
+
+        if (0 == gPlayStart->listOfAction.empty())
+        {
+            result = gThingManager->addActionSet(gFindGroup, gPlayStart, onAction);
+            if (OC_STACK_OK == result)
+            {
+                cout << "addActionSet(gPlayStart) was successful\n";
+            }
+            else
+            {
+                cout << "addActionSet(gPlayStart) was unsuccessful. result = " << result << endl;
+            }
+        }
+
+        if (0 == gPlayStop->listOfAction.empty())
+        {
+            result = gThingManager->addActionSet(gFindGroup, gPlayStop, onAction);
+            if (OC_STACK_OK == result)
+            {
+                cout << "addActionSet(gPlayStop) was successful\n";
+            }
+            else
+            {
+                cout << "addActionSet(gPlayStop) was unsuccessful. result = " << result << endl;
+            }
+        }
+    }
+    else
+    {
+        cout << "onGetChild : error - " << eCode << endl;
+    }
+}
+
+int main(int argc, char* argv[])
+{
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+    gThingManager = new ThingsManager();
+
+    int selectedMenu;
+    OCStackResult result;
+
+    try
+    {
+        while (true)
+        {
+            // some operations
+            cout << "(1) CREATE PHONE" << endl;
+            cout
+                    << "(11) FIND & JOIN GROUP | (12) ADD GROUP ACTION | (13) PLAY START"
+                    << " | (14) PLAY STOP"<< endl;
+            cout << "(15) DELETE GROUP ACTION | (16) LEAVE GROUP" << endl;
+            cout << "(21) DELETE PHONE" << endl;
+
+            std::cin >> selectedMenu;
+
+            if (selectedMenu == 1)
+            {
+                if (gPhoneResourceHandle)
+                {
+                    cout << "Phone resource is registered already." << endl;
+                    continue;
+                }
+
+                std::string resourceURi = "/core/phone";
+                std::string resourceTypeName = "core.phone";
+                std::string resourceInterface = DEFAULT_INTERFACE;
+
+                result = OCPlatform::registerResource(gPhoneResourceHandle, resourceURi,
+                        resourceTypeName, resourceInterface, NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "To register phone resource was successful\n";
+                }
+                else
+                {
+                    cout << "To register phone resource was unsuccessful. result = " << result
+                            << endl;
+                }
+            }
+            else if (selectedMenu == 11)
+            {
+                std::vector< std::string > types;
+                types.clear();
+                types.push_back(collectionResourceType);
+
+                result = gThingManager->findGroup(types, &onFindGroup);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Finding group was successful\n";
+                }
+                else
+                {
+                    cout << "Finding group was unsuccessful. result = " << result << endl;
+                }
+            }
+            else if (selectedMenu == 12)
+            {
+                if (!gFindGroup)
+                {
+                    cout << "gFindGroup is NULL. Please process step 1 and step 11 first." << endl;
+                    continue;
+                }
+
+                QueryParamsMap queryParamsMap;
+                result = gFindGroup->get("", DEFAULT_INTERFACE, queryParamsMap, onGetChild);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "gFindGroup->get was successful\n";
+                }
+                else
+                {
+                    cout << "gFindGroup->get was unsuccessful. result = " << result << endl;
+                }
+            }
+            else if (selectedMenu == 13)
+            {
+                if (!gFindGroup)
+                {
+                    cout << "gFindGroup is NULL. Please process step 1 and step 11 first." << endl;
+                    continue;
+                }
+
+                if (!gPlayStart)
+                {
+                    cout << "gPlayStart is NULL. Please process step 12 first." << endl;
+                    continue;
+                }
+
+                result = gThingManager->executeActionSet(gFindGroup, "playstart", onAction);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "DoAction(playstart) was successful\n";
+                }
+                else
+                {
+                    cout << "DoAction(playstart) was unsuccessful. result = " << result << endl;
+                }
+            }
+            else if (selectedMenu == 14)
+            {
+                if (!gFindGroup)
+                {
+                    cout << "gFindGroup is NULL. Please process step 1 and step 11 first." << endl;
+                    continue;
+                }
+
+                if (!gPlayStop)
+                {
+                    cout << "gPlayStop is NULL. Please process step 12 first." << endl;
+                    continue;
+                }
+
+                result = gThingManager->executeActionSet(gFindGroup, "playstop", onAction);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "DoAction(playstop) was successful\n";
+                }
+                else
+                {
+                    cout << "DoAction(playstop) was unsuccessful. result = " << result << endl;
+                }
+            }
+            else if (selectedMenu == 15)
+            {
+                if (!gFindGroup)
+                {
+                    cout << "gFindGroup is NULL. Please process step 1 and step 11 first." << endl;
+                    continue;
+                }
+
+                if (!gPlayStart)
+                {
+                    cout << "gPlayStart is NULL. Please process step 12 first." << endl;
+                    continue;
+                }
+
+                if (!gPlayStop)
+                {
+                    cout << "gPlayStop is NULL. Please process step 12 first." << endl;
+                    continue;
+                }
+
+                result = gThingManager->deleteActionSet(gFindGroup, "playstart", onAction);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Delete Action(playstart) was successful\n";
+                }
+                else
+                {
+                    cout << "Delete Action(playstart) was unsuccessful. result = " << result
+                            << endl;
+                }
+
+                result = gThingManager->deleteActionSet(gFindGroup, "playstop", onAction);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Delete Action(playstop) was successful\n";
+                }
+                else
+                {
+                    cout << "Delete Action(playstop) was unsuccessful. result = " << result << endl;
+                }
+
+                Action* a;
+                Capability* c;
+
+                for (auto actionIter = gPlayStart->listOfAction.begin();
+                        actionIter != gPlayStart->listOfAction.end(); ++actionIter)
+                {
+                    a = (*actionIter);
+
+                    for (auto capaIter = a->listOfCapability.begin();
+                            capaIter != a->listOfCapability.end(); ++capaIter)
+                    {
+                        c = (*capaIter);
+                        delete c;
+                    }
+
+                    delete a;
+                }
+
+                delete gPlayStart;
+                gPlayStart = NULL;
+
+                for (auto actionIter = gPlayStop->listOfAction.begin();
+                        actionIter != gPlayStop->listOfAction.end(); ++actionIter)
+                {
+                    a = (*actionIter);
+
+                    for (auto capaIter = a->listOfCapability.begin();
+                            capaIter != a->listOfCapability.end(); ++capaIter)
+                    {
+                        c = (*capaIter);
+                        delete c;
+                    }
+
+                    delete a;
+                }
+
+                delete gPlayStop;
+                gPlayStop = NULL;
+            }
+            else if (selectedMenu == 16)
+            {
+                if (NULL == gPhoneResourceHandle)
+                {
+                    cout
+                            << "Error! No resource to leave group. Register resource first!"
+                            << endl;
+                    continue;
+                }
+
+                result = gThingManager->leaveGroup(collectionResourceType, gPhoneResourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "Leaving group was successful\n";
+                }
+                else
+                {
+                    cout << "Leaving group was unsuccessful. result = " << result << endl;
+                }
+            }
+            else if (selectedMenu == 21)
+            {
+                if (NULL == gPhoneResourceHandle)
+                {
+                    cout
+                            << "Error! No resource to unregister. Register resource first!"
+                            << endl;
+                    continue;
+                }
+
+                result = OCPlatform::unregisterResource(gPhoneResourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "To unregister phone resource was successful\n";
+                }
+                else
+                {
+                    cout << "To unregister phone resource was unsuccessful. result = " << result
+                            << endl;
+                }
+                gPhoneResourceHandle = NULL;
+            }
+        }
+
+    }
+    catch (OCException& e)
+    {
+        //log(e.what());
+    }
+
+    return 0;
+}
+
diff --git a/service/things-manager/sampleapp/linux/groupsyncaction/speaker.cpp b/service/things-manager/sampleapp/linux/groupsyncaction/speaker.cpp
new file mode 100644 (file)
index 0000000..41abb36
--- /dev/null
@@ -0,0 +1,165 @@
+//******************************************************************
+//
+// Copyright 2014 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 <string>
+#include <cstdlib>
+#include <pthread.h>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ThingsManager.h"
+
+using namespace OC;
+
+OCEntityHandlerResult speakerEntityHandler(const std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "speakerEntityHandler:\n";
+
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+        std::string action;
+
+        if (requestFlag == RequestHandlerFlag::InitFlag)
+        {
+            cout << "\trequestFlag : Init\n";
+
+            // entity handler to perform resource initialization operations
+        }
+        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\trequestFlag : Request\n";
+
+            OCRepresentation rp = request->getResourceRepresentation();
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                cout << "\t\trequestType : GET\n";
+            }
+            else if (requestType == "PUT")
+            {
+                cout << "\t\trequestType : PUT\n";
+
+                action = rp.getValue< std::string >("volume");
+                cout << "\t\t\tvolume : " << action << endl;
+            }
+            else if (requestType == "POST")
+            {
+                cout << "\t\trequestType : POST\n";
+            }
+            else if (requestType == "DELETE")
+            {
+                cout << "\t\trequestType : DELETE\n";
+            }
+        }
+        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        {
+            cout << "\trequestFlag : Observer\n";
+        }
+    }
+    else
+    {
+        cout << "Request invalid" << endl;
+    }
+
+    return OC_EH_OK;
+}
+
+int main(int argc, char* argv[])
+{
+
+    // Create PlatformConfig object
+    PlatformConfig cfg
+    { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+    OCPlatform::Configure(cfg);
+
+    int selectedMenu;
+    OCStackResult result;
+    OCResourceHandle speakerResourceHandle = NULL;
+
+    try
+    {
+        while (true)
+        {
+            // some operations
+            cout << "(1) CREATE SPEAKER | (2) DELETE SPEAKER" << endl;
+
+            std::cin >> selectedMenu;
+
+            if (selectedMenu == 1)
+            {
+                if (speakerResourceHandle)
+                {
+                    cout << "Speaker resource is registered already." << endl;
+                    continue;
+                }
+
+                std::string resourceURi = "/core/speaker";
+                std::string resourceTypeName = "core.speaker";
+
+                std::string resourceInterface = DEFAULT_INTERFACE;
+
+                result = OCPlatform::registerResource(speakerResourceHandle, resourceURi,
+                        resourceTypeName, resourceInterface, speakerEntityHandler,
+                        OC_DISCOVERABLE | OC_OBSERVABLE);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "To register speaker resource was successful\n";
+                }
+                else
+                {
+                    cout << "To register speaker resource was unsuccessful\n";
+                }
+            }
+            else if (selectedMenu == 2)
+            {
+                if (NULL == speakerResourceHandle)
+                {
+                    cout
+                            << "Error! No resource to unregister. Register resource first!"
+                            << endl;
+                    continue;
+                }
+
+                result = OCPlatform::unregisterResource(speakerResourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "To unregister speaker resource was successful\n";
+                }
+                else
+                {
+                    cout << "To unregister speaker resource was unsuccessful\n";
+                }
+
+                speakerResourceHandle = NULL;
+            }
+        }
+    }
+    catch (OCException& e)
+    {
+        //log(e.what());
+    }
+
+    return 0;
+}
+
diff --git a/service/things-manager/sampleapp/linux/makefile b/service/things-manager/sampleapp/linux/makefile
new file mode 100644 (file)
index 0000000..092d768
--- /dev/null
@@ -0,0 +1,21 @@
+MAKE=make
+
+DIRLIST=configuration groupaction  groupsyncaction
+
+# Force metatargets to build:
+.PHONY: all clean
+
+all: build
+
+build:
+       @for subdir in ${DIRLIST} ; do \
+       ${MAKE} -C $${subdir} ; \
+       echo " " ; \
+       done
+       @echo " "
+
+clean:
+       @for subdir in ${DIRLIST} ; do \
+       ${MAKE} clean -C $${subdir} ; \
+       echo " " ; \
+       done
diff --git a/service/things-manager/sampleapp/linux/tgmclient/SConscript b/service/things-manager/sampleapp/linux/tgmclient/SConscript
deleted file mode 100644 (file)
index 2c347ff..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-##
-# linux sample app  build script
-##
-
-Import('env')
-
-# Add third party libraries
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-
-linux_sample_env = lib_env.Clone()
-######################################################################
-# Build flags
-######################################################################
-linux_sample_env.AppendUnique(CPPPATH = ['../../../sdk/inc'])
-linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-linux_sample_env.AppendUnique(LIBS = ['oc', 'octbstack', 'coap', 'oc_logger', 'TGMSDKLibrary'])
-
-if env.get('TARGET_OS') not in ['windows', 'winrt']:
-       linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-tgmclient = linux_sample_env.Program('tgmclient', 'tgmsdkclient.cpp')
-
-Alias("tgmclient_sample", tgmclient)
-env.AppendTarget('tgmclient_sample')
\ No newline at end of file
diff --git a/service/things-manager/sampleapp/linux/tgmclient/makefile b/service/things-manager/sampleapp/linux/tgmclient/makefile
deleted file mode 100644 (file)
index 7e2fe95..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-
-TGMROOT=../../../
-IOT_BASE=${TGMROOT}../../resource
-RST_NAME=.
-TARGET=tgmclient
-
-
-# C++ type Compile Flag define.
-CXX=g++
-CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
-
-CXX_INC        := -I../../ -I../../inc/ 
-CXX_INC        += -I${IOT_BASE}/include/ 
-CXX_INC += -I${IOT_BASE}/oc_logger/include
-CXX_INC        += -I${IOT_BASE}/csdk/stack/include 
-CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include 
-CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include 
-CXX_INC        += -I${IOT_BASE}/csdk/logger/include 
-
-CXX_LIB=-L""
-
-CXX_SRCPATH=${wildcard ../../src/*.cpp}
-CXX_SRCLIST=${notdir ${CXX_SRCPATH}}
-CXX_USESRCS=${filter-out ${EXCLUDE_LIST}, ${CXX_SRCLIST}}
-CXX_OBJLIST=${CXX_USESRCS:.cpp=.o}
-
-
-TGM = ../../
-SDK = ${TGMROOT}sdk
-TGM_INC = -I${TGMROOT}sdk/inc
-SDK_LIB = ${TGMROOT}sdk/build/linux/libTGMSDKLibrary.a
-
-LIB_OC_LOGGER := $(IOT_BASE)/oc_logger/lib/oc_logger.a
-
-LD_LIB := $(IOT_BASE)/release/obj/liboc.a  
-LD_LIB += $(IOT_BASE)/csdk/linux/release/liboctbstack.a 
-LD_LIB += $(LIB_OC_LOGGER)
-
-
-# Force metatargets to build:
-.PHONY: all clean
-
-all: ${TARGET} 
-
-${TARGET}: ./tgmsdkclient.cpp
-       $(CXX) $(CXX_FLAGS) -o ${TARGET} ./tgmsdkclient.cpp   $(CXX_INC)  ${LD_LIB} $(TGM_INC) $(SDK_LIB)
-       
-clean:
-       rm -f -v *.o ${TARGET}
-       
diff --git a/service/things-manager/sampleapp/linux/tgmclient/tgmsdkclient.cpp b/service/things-manager/sampleapp/linux/tgmclient/tgmsdkclient.cpp
deleted file mode 100644 (file)
index b1405ab..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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 <string>
-#include <cstdlib>
-#include <pthread.h>
-#include "OCPlatform.h"
-#include "OCApi.h"
-#include "TGMClient.h"
-
-using namespace OC;
-
-void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
-{
-    if (eCode == OC_STACK_OK)
-    {
-        std::cout << "GET request was successful" << std::endl;
-        std::cout << "Resource URI: " << rep.getUri() << std::endl;
-
-        AttributeMap dataMap = rep.getAttributeMap();
-        for (auto it = dataMap.begin(); it != dataMap.end(); ++it)
-        {
-            std::cout << "\t KEY:" << it->first << "  //  VALUE:" << it->second << std::endl;
-        }
-
-    }
-    else
-    {
-        std::cout << "onGET Response error: " << eCode << std::endl;
-        std::exit(-1);
-    }
-}
-
-void onFoundCandidate(std::vector< std::shared_ptr< OCResource > > resources)
-{
-    std::cout << "\n\n  FOUND CANDIDATE  \n\n";
-    for (unsigned int i = 0; i < resources.size(); ++i)
-    {
-        QueryParamsMap test;
-        resources.at(i)->get(test, &onGet);
-    }
-}
-
-int main(int argc, char* argv[])
-{
-
-    // Create PlatformConfig object
-    PlatformConfig cfg
-    { OC::ServiceType::InProc, OC::ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos };
-
-    OCPlatform::Configure(cfg);
-    TGMClient *tgmclient = new TGMClient();
-
-    int selectedMenu;
-
-    try
-    {
-        std::vector < std::string > types;
-
-        while (true)
-        {
-            // some operations
-            std::cout << "ADD  | (1)TV | (2)LIGHT | (3)CURTAIN | (4)RESET |" << std::endl;
-            std::cout << "FIND | (5) ONCE | (6) 10sec |" << std::endl;
-
-            std::cin >> selectedMenu;
-
-            if (selectedMenu == 1)
-            {
-                types.push_back("core.tv");
-            }
-            else if (selectedMenu == 2)
-            {
-                types.push_back("core.light");
-            }
-            else if (selectedMenu == 3)
-            {
-                types.push_back("core.curtain");
-            }
-            else if (selectedMenu == 4)
-            {
-                types.clear();
-            }
-            else if (selectedMenu == 5)
-            {
-                tgmclient->findCandidateResources(types, &onFoundCandidate);
-            }
-            else if (selectedMenu == 6)
-            {
-                tgmclient->findCandidateResources(types, &onFoundCandidate, 10);
-            }
-
-        }
-
-    }
-    catch (OCException& e)
-    {
-        //log(e.what());
-    }
-
-    return 0;
-}
-
index 1cadc89..0e5ec03 100644 (file)
@@ -15,13 +15,14 @@ CXX=g++
 CXX_FLAGS=-std=c++0x -Wall -pthread -DLINUX -ldl
 
 
-CXX_INC        := -I../../ -I../../inc/ 
+CXX_INC        := -I../../ -I../../inc/ -I../../src/
 CXX_INC        += -I${IOT_BASE}/include/ 
 CXX_INC += -I${IOT_BASE}/oc_logger/include
 CXX_INC        += -I${IOT_BASE}/csdk/stack/include 
 CXX_INC        += -I${IOT_BASE}/csdk/ocsocket/include 
 CXX_INC        += -I${IOT_BASE}/csdk/ocrandom/include 
 CXX_INC        += -I${IOT_BASE}/csdk/logger/include 
+CXX_INC        += -I${IOT_BASE}/dependencies/cereal/include
 
 CXX_LIB=-L""
 
diff --git a/service/things-manager/sdk/inc/TGMClient.h b/service/things-manager/sdk/inc/TGMClient.h
deleted file mode 100644 (file)
index a087ee6..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/// @file   TGMClient.h
-
-/// @brief  This file contains the declaration of classes and its members related to TGMClient.
-
-#ifndef __OC_TGMCLIENT__
-#define __OC_TGMCLIENT__
-
-#include <string>
-#include <vector>
-#include <map>
-#include <cstdlib>
-#include "OCPlatform.h"
-#include "OCApi.h"
-
-using namespace OC;
-
-typedef std::function< void(std::vector< std::shared_ptr< OCResource > >) > CandidateCallback;
-typedef std::function< void(std::vector< std::shared_ptr< OCResource > >) > CollectionPresenceCallback;
-
-class TGMClient
-{
-public:
-    /**
-     * Constructor for TGMClient. Constructs a new TGMClient
-     */
-    TGMClient(void);
-
-    /**
-     * Virtual destructor
-     */
-    ~TGMClient(void);
-
-    /**
-     * API for candidate resources discovery.
-     * Callback only call when all resource types found.
-     *
-     * @param resourceTypes - required resource types(called "candidate")
-     * @param candidateCallback - callback. OCResource vector.
-     *
-     * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-     *
-     * NOTE: OCStackResult is defined in ocstack.h.
-     */
-    OCStackResult findCandidateResources(std::vector< std::string > resourceTypes,
-            CandidateCallback callback, int waitsec = -1);
-
-    /**
-     * API for Collection member's state subscribe.
-     *
-     * NOTE: NOT IMPLEMENT YET
-     */
-    OCStackResult subscribeCollectionPresence(OCResourceHandle&, CollectionPresenceCallback)
-    {
-        return OC_STACK_NOTIMPL;
-    }
-
-private:
-
-    void onFoundResource(std::shared_ptr< OCResource > resource, int waitsec);
-    void findPreparedRequest(std::map< std::vector< std::string >, CandidateCallback > &request);
-    void lazyCallback(int second);
-
-};
-
-#endif  /* __OC_TGMCLIENT__*/
diff --git a/service/things-manager/sdk/inc/ThingsManager.h b/service/things-manager/sdk/inc/ThingsManager.h
new file mode 100644 (file)
index 0000000..de7c365
--- /dev/null
@@ -0,0 +1,408 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file   ThingsManager.h
+///
+/// @brief  This file contains the declaration of  ThingsManager class
+///         and its members related to ThingsManager.
+
+#ifndef __OC_THINGSMANAGER__
+#define __OC_THINGSMANAGER__
+
+#include <string>
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "GroupManager.h"
+
+using namespace OC;
+
+namespace OIC
+{
+    /**
+     * @class  ThingsManager
+     * @brief  This class provides a set of functions regarding group management,
+     *          synchronization of group, configuration of things, and diagnostics about things.
+     *
+     */
+    class ThingsManager
+    {
+    public:
+        /**
+         * Constructor for ThingsManager
+         */
+        ThingsManager(void);
+
+        /**
+         * Virtual destructor for ThingsManager
+         */
+        ~ThingsManager(void);
+
+        /**
+         * API for discoverying candidate resources.
+         * Callback is called  when all resource types are found.
+         *
+         * @param resourceTypes - required resource types(called "candidate")
+         * @param candidateCallback - callback. Returns OCResource vector.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult findCandidateResources(std::vector< std::string > resourceTypes,
+                std::function< void(std::vector< std::shared_ptr< OCResource > >) > callback,
+                int waitsec = -1);
+
+        /**
+         * API for subscribing child's state.
+         *
+         * @param resource - collection resource for subscribing presence of all child resources.
+         * @param callback - callback funcion for result of child's presence.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult subscribeCollectionPresence(std::shared_ptr< OCResource > resource,
+                std::function< void(std::string, OCStackResult) > callback);
+
+        /**
+         * API for register and bind resource to group.
+         *
+         * @param childHandle - child resource handle. It will be filled from resource param.
+         * @param resource - resource for register and bind to group. It has all data.
+         * @param collectionHandle - collection resource handle. It will be added child resource.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult bindResourceToGroup(OCResourceHandle& childHandle,
+                std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle);
+
+        // Group Synchronization
+
+        /**
+         * API for finding a specific remote group when a resource tries to join a group.
+         * Callback is called when a group is found or not.
+         *
+         * @param collectionResourceTypes - resource types of a group to find and join
+         * @param callback - callback. It has OCResource param.
+         *                    If a group is found, OCResource has the group resource.
+         *                    Otherwise, OCResource is NULL.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult findGroup(std::vector< std::string > collectionResourceTypes,
+                FindCallback callback);
+
+        /**
+         * API for creating a new group.
+         *
+         * @param collectionResourceType - resource type of a group to create
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult createGroup(std::string collectionResourceType);
+
+        /**
+         * API for joining a group. This API is used when a resource that has a group tries
+         * to find a specific remote resource and makes it join a group
+         *
+         * @param collectionResourceType - resource type of a group to join.
+         * @param resourceHandle - resource handle to join a group.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult joinGroup(std::string collectionResourceType,
+                OCResourceHandle resourceHandle);
+
+        /**
+         * API for joining a group. This API is used when a resource that
+         * doesn't have a group tries to find and join a specific remote group.
+         *
+         * @param resource - group resource pointer to join.
+         *                   It can be the callback result of findGroup().
+         * @param resourceHandle - resource handle to join a group.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult joinGroup(const std::shared_ptr< OCResource > resource,
+                OCResourceHandle resourceHandle);
+
+        /**
+         * API for leaving a joined group.
+         *
+         * @param collectionResourceType - resource type of a group to leave.
+         * @param resourceHandle - resource handle to leave a group.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult leaveGroup(std::string collectionResourceType,
+                OCResourceHandle resourceHandle);
+
+        /**
+         * API for deleting a group.
+         *
+         * @param collectionResourceType - resource type of a group to delete.
+         *
+         * @return void
+         */
+        void deleteGroup(std::string collectionResourceType);
+
+        /**
+         * API for getting a list of joined groups.
+         *
+         * @param void
+         *
+         * @return std::map - return value of this API.
+         *                  It returns group resource type and group resource handle as a map type.
+         */
+        std::map< std::string, OCResourceHandle > getGroupList(void);
+
+        // Things Configuration
+
+        /**
+         * API for updating configuration value of multiple things of a target group
+         * or a single thing.
+         * Callback is called when a response arrives.
+         * Before using the below function, a developer should acquire a resource pointer of
+         * (collection) resource that he wants to send a request by calling findResource() function
+         * provided in OCPlatform. And he should also notice a "Configuration Name" term which
+         * represents a nickname of a target attribute of a resource that he wants to update.
+         * The base motivation to introduce the term is to avoid a usage of URI to access a resource
+         * from a developer. Thus, a developer should know which configuration names are supported
+         * by Things Configuration class and what the configuration name means.
+         * To get a list of supported configuration names,
+         * use getListOfSupportedConfigurationUnits()
+         * function, which provides the list in JSON format.
+         *
+         * @param resource - resource pointer representing the target group or the single thing.
+         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
+         *                         (e.g., installedlocation, currency, (IP)address)
+         *                         Value : a value to be updated
+         * @param callback - callback for updateConfigurations.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult updateConfigurations(std::shared_ptr< OCResource > resource,
+                std::map< std::string, std::string > configurations,
+                std::function<
+                        void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                const int eCode) > callback);
+
+        /**
+         * API for getting configuration value of multiple things of a target group
+         * or a single thing.
+         * Callback is called when a response arrives.
+         *
+         * @param resource - resource pointer representing the target group or the single thing.
+         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource.
+         * @param callback - callback for getConfigurations.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult getConfigurations(std::shared_ptr< OCResource > resource,
+                std::vector< std::string > configurations,
+                std::function<
+                        void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                const int eCode) > callback);
+
+        /**
+         * API for showing the list of supported configuration units (configurable parameters)
+         * Callback is called when a response arrives.
+         *
+         * @param void
+         * @return std::string - return value of this API.
+         *                       It returns the list in JSON format
+         */
+        std::string getListOfSupportedConfigurationUnits();
+
+        /**
+         * API for boostrapping system configuration parameters from a bootstrap server.
+         * Callback call when a response from the bootstrap server arrives.
+         *
+         * @param callback - callback for doBootstrap.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult doBootstrap(
+                std::function<
+                        void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                const int eCode) > callback);
+
+        // Things Diagnostics
+
+        /**
+         * API to let thing(device) reboot.
+         * The target thing could be a group of multiple things or a single thing.
+         * Callback is called when a response arrives.
+         *
+         * @param resource - resource pointer representing the target group
+         * @param callback - callback for reboot.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult reboot(std::shared_ptr< OCResource > resource,
+                std::function<
+                        void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                const int eCode) > callback);
+
+        /**
+         * API for factory reset on thing(device).
+         * The target thing could be a group of multiple things or a single thing.
+         * Callback is called when a response arrives.
+         *
+         * @param resource - resource pointer representing the target group
+         * @param callback - callback for factoryReset.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult factoryReset(std::shared_ptr< OCResource > resource,
+                std::function<
+                        void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                const int eCode) > callback);
+
+        // Group Action.
+
+        /**
+         * API for extracting Action Set string from the Action Set class instance
+         *
+         * @param newActionSet - pointer of Action Set
+         *
+         * @return std::string - return value of this API.
+         *                                          It returns Action Set String.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        std::string getStringFromActionSet(const ActionSet *newActionSet);
+
+        /**
+         * API for extrracting Action Set class instance from Action Set String.
+         *
+         * @param desc - description of Action set
+         *
+         * @return ActionSet* - return value of this API.
+         *                      It returns pointer of ActionSet.
+         */
+        ActionSet* getActionSetfromString(std::string desc);
+
+        /**
+         * API for adding an Action Set.
+         * Callback is called when the response of PUT operation arrives.
+         *
+         * @param resource - resource pointer of the group resource
+         * @param newActionSet - pointer of Action Set
+         * @param callback - callback for PUT operation.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult addActionSet(std::shared_ptr< OCResource > resource,
+                const ActionSet* newActionSet, PutCallback cb);
+
+        /**
+         * API for executing the Action Set.
+         * Callback is called when the response of  POST operation arrives.
+         *
+         * @param resource - resource pointer of the group resource
+         * @param actionsetName - Action Set name for executing the Action set
+         * @param callback - callback for POST operation.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
+                std::string actionsetName, PostCallback cb);
+
+        /**
+         * API for reading the Action Set.
+         * Callback is called when the response of  GET operation arrives.
+         *
+         * @param resource - resource pointer of the group resource
+         * @param actionsetName - Action Set name for reading the Action set
+         * @param callback - callback for GET operation.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult getActionSet(std::shared_ptr< OCResource > resource,
+                std::string actionsetName, GetCallback cb);
+
+        /**
+         * API for removing the Action Set.
+         * Callback is called when the response of  POST operation arrives.
+         *
+         * @param resource - resource pointer of the group resource
+         * @param actionsetName - Action Set name for removing the Action set
+         * @param callback - callback for POST operation.
+         *
+         * @return OCStackResult - return value of this API.
+         *                         It returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult deleteActionSet(std::shared_ptr< OCResource > resource,
+                std::string actionsetName, PostCallback);
+
+    };
+}
+#endif  /* __OC_THINGSMANAGER__*/
diff --git a/service/things-manager/sdk/src/GroupManager.cpp b/service/things-manager/sdk/src/GroupManager.cpp
new file mode 100644 (file)
index 0000000..aed8734
--- /dev/null
@@ -0,0 +1,572 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file    GroupManager.cpp
+///  @brief
+
+#include "GroupManager.h"
+#include <algorithm>
+#include <thread>
+#include <unistd.h>
+
+#include <string.h>
+
+#define PLAIN_DELIMITER "\""
+#define ACTION_DELIMITER "*"
+#define DESC_DELIMITER "|"
+#define ATTR_DELIMITER "="
+
+using namespace OC;
+
+namespace OIC
+{
+std::map< std::vector< std::string >, CandidateCallback > candidateRequest;
+std::map< std::vector< std::string >, CandidateCallback > candidateRequestForTimer;
+std::map< std::string, std::map< std::string, std::shared_ptr< OCResource > > > rtForResourceList;
+std::vector< std::string > allFoundResourceTypes;
+
+template< typename T >
+bool IsSubset(std::vector< T > full, std::vector< T > sub)
+{
+    std::sort(full.begin(), full.end());
+    std::sort(sub.begin(), sub.end());
+    return std::includes(full.begin(), full.end(), sub.begin(), sub.end());
+}
+std::vector< std::string > &str_split(const std::string &s, char delim,
+        std::vector< std::string > &elems)
+{
+    std::stringstream ss(s);
+    std::string item;
+    while (std::getline(ss, item, delim))
+    {
+        elems.push_back(item);
+    }
+    return elems;
+}
+
+std::vector< std::string > str_split(const std::string &s, char delim)
+{
+    std::vector< std::string > elems;
+    str_split(s, delim, elems);
+    return elems;
+}
+
+void GroupManager::onFoundResource(std::shared_ptr< OCResource > resource, int waitsec)
+{
+
+    std::string resourceURI;
+    std::string hostAddress;
+    try
+    {
+        // Do some operations with resource object.
+        if (resource)
+        {
+
+            std::cout << "DISCOVERED Resource:" << std::endl;
+            // Get the resource URI
+            resourceURI = resource->uri();
+            std::cout << "\tURI of the resource: " << resourceURI << std::endl;
+
+            // Get the resource host address
+            hostAddress = resource->host();
+            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
+
+            // Get the resource types
+            std::cout << "\tList of resource types: " << std::endl;
+
+            hostAddress.append(resourceURI);
+
+            for (auto &resourceTypes : resource->getResourceTypes())
+            {
+                std::cout << "\t\t" << resourceTypes << std::endl;
+
+                if (std::find(allFoundResourceTypes.begin(), allFoundResourceTypes.end(),
+                        resourceTypes) == allFoundResourceTypes.end())
+                {
+                    allFoundResourceTypes.push_back(resourceTypes);
+                }
+
+                rtForResourceList[resourceTypes][hostAddress] = resource;
+            }
+
+            // Get the resource interfaces
+            std::cout << "\tList of resource interfaces: " << std::endl;
+            for (auto &resourceInterfaces : resource->getResourceInterfaces())
+            {
+                std::cout << "\t\t" << resourceInterfaces << std::endl;
+            }
+
+            if (waitsec == -1)
+            {
+                findPreparedRequest(candidateRequest);
+            }
+        }
+        else
+        {
+            // Resource is invalid
+            std::cout << "Resource is invalid" << std::endl;
+        }
+
+    }
+    catch (std::exception& e)
+    {
+        //log(e.what());
+    }
+}
+
+GroupManager::GroupManager(void)
+{
+    ;
+}
+
+/**
+ * Virtual destructor
+ */
+GroupManager::~GroupManager(void)
+{
+    candidateRequest.clear();
+    candidateRequestForTimer.clear();
+    rtForResourceList.clear();
+    allFoundResourceTypes.clear();
+}
+
+void GroupManager::findPreparedRequest(
+        std::map< std::vector< std::string >, CandidateCallback > &request)
+{
+    std::vector< std::shared_ptr< OCResource > > resources;
+
+    for (auto it = request.begin(); it != request.end();)
+    {
+
+        if (IsSubset(allFoundResourceTypes, it->first))
+        {
+            //std::cout << "IS SUBSET !!! \n";
+
+            for (unsigned int i = 0; i < it->first.size(); ++i)
+            {
+
+                for (auto secondIt = rtForResourceList[it->first.at(i)].begin();
+                        secondIt != rtForResourceList[it->first.at(i)].end(); ++secondIt)
+                {
+                    resources.push_back(secondIt->second);
+                }
+            }
+
+            it->second(resources);
+
+            //TODO : decide policy - callback only once
+            request.erase(it++);
+        }
+        else
+        {
+            ++it;
+        }
+
+    }
+
+}
+
+void GroupManager::lazyCallback(int second)
+{
+    sleep(second);
+    findPreparedRequest(candidateRequestForTimer);
+
+}
+
+OCStackResult GroupManager::findCandidateResources(std::vector< std::string > resourceTypes,
+        CandidateCallback callback, int waitsec)
+{
+    if (resourceTypes.size() < 1)
+    {
+        return OC_STACK_ERROR;
+    }
+
+    std::sort(resourceTypes.begin(), resourceTypes.end());
+    resourceTypes.erase(std::unique(resourceTypes.begin(), resourceTypes.end()),
+            resourceTypes.end());
+
+    if (waitsec != -1)
+    {
+        candidateRequestForTimer.insert(std::make_pair(resourceTypes, callback));
+    }
+    else
+    {
+        candidateRequest.insert(std::make_pair(resourceTypes, callback));
+    }
+
+    for (unsigned int i = 0; i < resourceTypes.size(); ++i)
+    {
+        std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
+        std::string query = "coap://224.0.1.187/oc/core?rt=";
+        query.append(resourceTypes.at(i));
+        OCPlatform::findResource("", query.c_str(),
+                std::function < void(std::shared_ptr < OCResource > resource)
+                        > (std::bind(&GroupManager::onFoundResource, this, std::placeholders::_1,
+                                waitsec)));
+    }
+
+    if (waitsec != -1)
+    {
+        std::thread exec(
+                std::function< void(int second) >(
+                        std::bind(&GroupManager::lazyCallback, this, std::placeholders::_1)),
+                waitsec);
+        exec.detach();
+    }
+
+    return OC_STACK_OK;
+}
+
+/*
+ Presence Check
+ */
+
+std::map< std::string, CollectionPresenceCallback > presenceCallbacks;
+
+// Callback to presence
+void GroupManager::collectionPresenceHandler(OCStackResult result, const unsigned int nonce,
+        const std::string& hostAddress, std::string host, std::string uri)
+{
+    std::cout << "uri : " << uri << std::endl;
+    std::cout << "host : " << host << std::endl;
+    std::cout << "result : " << result << std::endl;
+    switch (result)
+    {
+        case OC_STACK_OK:
+            std::cout << "Nonce# " << nonce << std::endl;
+            break;
+        case OC_STACK_PRESENCE_STOPPED:
+            std::cout << "Presence Stopped\n";
+            break;
+        case OC_STACK_PRESENCE_DO_NOT_HANDLE:
+            std::cout << "Presence do not handle\n";
+            break;
+        case OC_STACK_PRESENCE_TIMEOUT:
+            std::cout << "Presence TIMEOUT\n";
+            break;
+        default:
+            std::cout << "Error\n";
+            break;
+    }
+
+    if (presenceCallbacks.find(uri) != presenceCallbacks.end())
+    {
+        (presenceCallbacks.find(uri)->second)(uri, result);
+    }
+}
+
+void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
+        CollectionPresenceCallback callback)
+{
+    std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+    /* //bug not found
+     if(rep.hasAttribute("name"))
+     {
+     std::cout << "\tRoom name: " << rep.getValue<std::string>("name") << std::endl;
+     }
+     */
+    std::vector< OCRepresentation > children = rep.getChildren();
+
+    for (auto oit = children.begin(); oit != children.end(); ++oit)
+    {
+        std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+        std::vector< std::string > hostAddressVector = str_split(oit->getUri(), '/');
+        std::string hostAddress = "";
+        for (unsigned int i = 0; i < hostAddressVector.size(); ++i)
+        {
+            if (i < 3)
+            {
+                hostAddress.append(hostAddressVector.at(i));
+                if (i != 2)
+                {
+                    hostAddress.append("/");
+                }
+            }
+        }
+
+        std::vector< std::string > resourceTypes = oit->getResourceTypes();
+        for (unsigned int i = 0; i < resourceTypes.size(); ++i)
+        {
+            std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
+        }
+
+        std::string resourceType = "core.";
+        resourceType.append(str_split(oit->getUri(), '/').at(4));
+        std::cout << "\t\tconvertRT : " << resourceType << std::endl;
+        std::cout << "\t\thost : " << hostAddress << std::endl;
+        OCPlatform::OCPresenceHandle presenceHandle;
+        OCStackResult result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
+                resourceType,
+                std::function<
+                        void(OCStackResult result, const unsigned int nonce,
+                                const std::string& hostAddress) >(
+                        std::bind(&GroupManager::collectionPresenceHandler, this,
+                                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3,
+                                hostAddress, oit->getUri())));
+
+        if (result == OC_STACK_OK)
+        {
+            std::cout << "\t\tOK!" << std::endl;
+            presenceCallbacks.insert(std::make_pair(oit->getUri(), callback));
+        }
+        else
+        {
+            callback("", OC_STACK_ERROR);
+        }
+
+    }
+}
+
+void GroupManager::onGetForPresence(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+        const int eCode, CollectionPresenceCallback callback)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        std::cout << "GET request was successful" << std::endl;
+        std::cout << "Resource URI: " << rep.getUri() << std::endl;
+
+        checkCollectionRepresentation(rep, callback);
+
+    }
+    else
+    {
+        std::cout << "onGET Response error: " << eCode << std::endl;
+        callback("", OC_STACK_ERROR);
+        std::exit(-1);
+    }
+}
+
+OCStackResult GroupManager::subscribeCollectionPresence(
+        std::shared_ptr< OCResource > collectionResource, CollectionPresenceCallback callback)
+{
+    OCStackResult result = OC_STACK_OK;
+    //callback("core.room",OC_STACK_OK);
+
+    QueryParamsMap queryParam;
+
+    //parameter 1 = resourceType
+    collectionResource->get("", DEFAULT_INTERFACE, queryParam,
+            std::function<
+                    void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                            const int eCode) >(
+                    std::bind(&GroupManager::onGetForPresence, this, std::placeholders::_1,
+                            std::placeholders::_2, std::placeholders::_3, callback)));
+
+    return result;
+}
+
+/*
+ Group Action
+ */
+
+std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
+{
+    std::string message = "";
+
+    message = newActionSet->actionsetName;
+    message.append("*");
+    for (auto iterAction = newActionSet->listOfAction.begin();
+            iterAction != newActionSet->listOfAction.end(); iterAction++)
+    {
+        message.append("uri=");
+        message.append((*iterAction)->target);
+        message.append("|");
+
+        for (auto iterCapa = (*iterAction)->listOfCapability.begin();
+                iterCapa != (*iterAction)->listOfCapability.end(); iterCapa++)
+        {
+            message.append((*iterCapa)->capability);
+            message.append("=");
+            message.append((*iterCapa)->status);
+
+            if (iterCapa + 1 != (*iterAction)->listOfCapability.end())
+                message.append("|");
+        }
+
+        if (iterAction + 1 != newActionSet->listOfAction.end())
+        {
+            message.append("*");
+        }
+    }
+
+    return message;
+}
+
+ActionSet* GroupManager::getActionSetfromString(std::string desc)
+{
+
+    char *token = NULL;
+    char *plainText = NULL;
+    char *plainPtr = NULL;
+
+    ActionSet *actionset = new ActionSet();
+    plainText = new char[(desc.length() + 1)];
+    strcpy(plainText, desc.c_str());
+
+    token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);
+
+    if (token != NULL)
+    {
+        actionset->actionsetName = std::string(token);
+        token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
+    }
+    else
+    {
+        delete actionset;
+        delete[] plainText;
+        return NULL;
+    }
+
+    while (token)
+    {
+        char *descPtr = NULL;
+        char *desc = new char[(strlen(token) + 1)];
+
+        if (desc != NULL)
+        {
+            Action *action = NULL;
+            strcpy(desc, token);
+            token = strtok_r(desc, DESC_DELIMITER, &descPtr);
+
+            // cout << "desc :: " << token << endl;
+            while (token != NULL)
+            {
+                char *attrPtr = NULL;
+                char *attr = new char[(strlen(token) + 1)];
+
+                strcpy(attr, token);
+
+                // cout << "attr :: " << attr << endl;
+
+                token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
+                while (token != NULL)
+                {
+                    if (strcmp(token, "uri") == 0)
+                    {
+                        token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
+                        action = new Action();
+
+                        if (action != NULL)
+                        {
+                            action->target = std::string(token);
+                        }
+                        else
+                        {
+                            delete actionset;
+                            delete[] attr;
+                            delete desc;
+                            delete[] plainText;
+                            return NULL;
+                        }
+                    }
+                    else
+                    {
+                        Capability *capa = new Capability();
+                        capa->capability = std::string(token);
+                        token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
+                        capa->status = std::string(token);
+
+                        if (action != NULL)
+                        {
+                            action->listOfCapability.push_back(capa);
+                        }
+                        else
+                        {
+                            delete capa;
+                            delete actionset;
+                            delete[] attr;
+                            delete[] plainText;
+                            delete desc;
+                            return NULL;
+                        }
+                    }
+
+                    token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
+                }
+
+                delete[] attr;
+                token = strtok_r(NULL, DESC_DELIMITER, &descPtr);
+            }
+
+            actionset->listOfAction.push_back(action);
+            //delete action;
+        }
+        else
+        {
+            delete actionset;
+            delete[] plainText;
+            return NULL;
+        }
+
+        delete[] desc;
+
+        token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
+    }
+
+    delete plainText;
+    return actionset;
+}
+
+OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
+        const ActionSet* newActionSet, PutCallback cb)
+{
+    // BUILD message of ActionSet which it is included delimiter.
+    std::string message = getStringFromActionSet(newActionSet);
+    OCRepresentation rep;
+
+    rep.setValue("ActionSet", message);
+
+    return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
+            QueryParamsMap(), cb);
+}
+
+OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
+        std::string actionsetName, PostCallback cb)
+{
+    OCRepresentation rep;
+
+    rep.setValue("DoAction", actionsetName);
+    return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
+            QueryParamsMap(), cb);
+}
+
+OCStackResult GroupManager::getActionSet(std::shared_ptr< OCResource > resource,
+        std::string actionsetName, PostCallback cb)
+{
+    OCRepresentation rep;
+
+    rep.setValue("GetActionSet", actionsetName);
+
+    return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
+            QueryParamsMap(), cb);
+}
+
+OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resource,
+        std::string actionsetName, PutCallback cb)
+{
+    OCRepresentation rep;
+
+    rep.setValue("DelActionSet", actionsetName);
+
+    return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
+            QueryParamsMap(), cb);
+}
+}
diff --git a/service/things-manager/sdk/src/GroupManager.h b/service/things-manager/sdk/src/GroupManager.h
new file mode 100644 (file)
index 0000000..d0dad45
--- /dev/null
@@ -0,0 +1,151 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file   GroupManager.h
+
+/// @brief  This file contains the declaration of classes and its members related to GroupManager
+
+#ifndef __OC_GROUPMANAGER__
+#define __OC_GROUPMANAGER__
+
+#include <string>
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+
+namespace OIC
+{
+typedef std::function< void(std::vector< std::shared_ptr< OCResource > >) > CandidateCallback;
+typedef std::function< void(std::string, OCStackResult) > CollectionPresenceCallback;
+
+typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const int) > GetCallback;
+typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const int) > PostCallback;
+typedef std::function< void(const HeaderOptions&, const OCRepresentation&, const int) > PutCallback;
+
+class Capability
+{
+public:
+    std::string capability;
+    std::string status;
+};
+
+class Action
+{
+public:
+    Action() :
+            target("")
+    {
+    }
+    ~Action()
+    {
+        listOfCapability.clear();
+    }
+    std::string target;
+
+    std::vector< Capability* > listOfCapability;
+};
+
+class ActionSet
+{
+public:
+    ActionSet() :
+            actionsetName("")
+    {
+    }
+    ~ActionSet()
+    {
+        listOfAction.clear();
+    }
+    std::string actionsetName;
+
+    std::vector< Action* > listOfAction;
+};
+
+class GroupManager
+{
+public:
+    /**
+     * Constructor for GroupManager. Constructs a new GroupManager
+     */
+    GroupManager(void);
+
+    /**
+     * Virtual destructor
+     */
+    ~GroupManager(void);
+
+    /**
+     * API for candidate resources discovery.
+     * Callback only call when all resource types found.
+     *
+     * @param resourceTypes - required resource types(called "candidate")
+     * @param candidateCallback - callback. OCResource vector.
+     *
+     * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+     *
+     * NOTE: OCStackResult is defined in ocstack.h.
+     */
+    OCStackResult findCandidateResources(std::vector< std::string > resourceTypes,
+            CandidateCallback callback, int waitsec = -1);
+
+    /**
+     * API for Collection member's state subscribe.
+     *
+     * NOTE: NOT IMPLEMENT YET
+     */
+    OCStackResult subscribeCollectionPresence(std::shared_ptr< OCResource > resource,
+            CollectionPresenceCallback);
+
+private:
+
+    void onFoundResource(std::shared_ptr< OCResource > resource, int waitsec);
+    void findPreparedRequest(std::map< std::vector< std::string >, CandidateCallback > &request);
+    void lazyCallback(int second);
+
+    void onGetForPresence(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode, CollectionPresenceCallback callback);
+    void checkCollectionRepresentation(const OCRepresentation& rep,
+            CollectionPresenceCallback callback);
+    void collectionPresenceHandler(OCStackResult result, const unsigned int nonce,
+            const std::string& hostAddress, std::string host, std::string uri);
+
+    /**
+     *   API for Collection(Group) action.
+     */
+
+public:
+    std::string getStringFromActionSet(const ActionSet *newActionSet);
+    ActionSet* getActionSetfromString(std::string desc);
+
+    OCStackResult addActionSet(std::shared_ptr< OCResource > resource,
+            const ActionSet* newActionSet, PutCallback cb);
+    OCStackResult executeActionSet(std::shared_ptr< OCResource > resource,
+            std::string actionsetName, PostCallback cb);
+    OCStackResult getActionSet(std::shared_ptr< OCResource > resource, std::string actionsetName,
+            PostCallback cb);
+    OCStackResult deleteActionSet(std::shared_ptr< OCResource > resource, std::string actionsetName,
+            PostCallback);
+};
+}
+#endif  /* __OC_GROUPMANAGER__*/
diff --git a/service/things-manager/sdk/src/GroupSynchronization.cpp b/service/things-manager/sdk/src/GroupSynchronization.cpp
new file mode 100644 (file)
index 0000000..dd2c96c
--- /dev/null
@@ -0,0 +1,1277 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file    GroupSynchronization.cpp
+/// @brief
+
+#include "GroupSynchronization.h"
+
+using namespace OC;
+
+namespace OIC
+{
+
+GroupSynchronization* GroupSynchronization::groupSyncnstance = NULL;
+
+GroupSynchronization* GroupSynchronization::getInstance()
+{
+    if (groupSyncnstance == NULL)
+    {
+        groupSyncnstance = new GroupSynchronization();
+    }
+    return groupSyncnstance;
+}
+
+void GroupSynchronization::deleteInstance()
+{
+    if (groupSyncnstance)
+    {
+        delete groupSyncnstance;
+        groupSyncnstance = NULL;
+    }
+}
+
+OCStackResult GroupSynchronization::findGroup(
+        std::vector< std::string > collectionResourceTypes, FindCallback callback)
+{
+    cout << "GroupSynchronization::findGroup" << endl;
+
+    foundGroupResourceList.clear();
+
+    findCallback = callback;
+
+    for (unsigned int i = 0; i < collectionResourceTypes.size(); ++i)
+    {
+        std::string query = "coap://224.0.1.187/oc/core?rt=";
+        query.append(collectionResourceTypes.at(i));
+        cout << "GroupSynchronization::findGroup - " << query << endl;
+
+        OCPlatform::findResource("", query,
+                std::bind(&GroupSynchronization::onFindGroup, this, std::placeholders::_1));
+    }
+
+    // thread to check if GroupSynchronization::onFoundGroup is called or not.
+    std::thread t(std::bind(&GroupSynchronization::checkFindGroup, this));
+    t.detach();
+
+    return OC_STACK_OK;
+}
+
+OCStackResult GroupSynchronization::createGroup(std::string collectionResourceType)
+{
+    foundGroupResourceList.clear();
+
+    OCResourceHandle collectionResHandle = NULL;
+    OCResourceHandle groupSyncResHandle = NULL;
+
+    if (0 != collectionResourceType.length())
+    {
+        cout << "GroupSynchronization::createGroup - The created group is added." << endl;
+
+        OCStackResult result;
+
+        // creating master collection resource
+        std::string collectionUri = "/" + collectionResourceType;
+        int i;
+        while ((i = collectionUri.find(".")) != std::string::npos)
+        {
+            collectionUri.replace(i, 1, "/");
+        }
+        cout << "GroupSynchronization::createGroup : collection uri - " << collectionUri
+                << ", type - " << collectionResourceType << endl;
+
+        std::string resourceInterface = DEFAULT_INTERFACE;
+
+        result = OCPlatform::registerResource(collectionResHandle, collectionUri,
+                collectionResourceType, resourceInterface, NULL,
+                OC_DISCOVERABLE | OC_OBSERVABLE);
+        if (result != OC_STACK_OK)
+        {
+            cout << "To register resource (" << collectionUri << ") was unsuccessful. result - "
+                    << result << endl;
+            goto Error;
+        }
+
+        OCPlatform::bindInterfaceToResource(collectionResHandle, GROUP_INTERFACE);
+        if (result != OC_STACK_OK)
+        {
+            cout << "To bind Interface (collection) was unsuccessful. result - " << result
+                    << endl;
+        }
+
+        collectionResourceHandleList[collectionResourceType] = collectionResHandle;
+
+        // creating master group sync resource
+        std::string groupSyncUri = collectionUri + "/groupsync";
+        std::string groupSyncResType = collectionResourceType + ".groupsync";
+
+//        cout << "GroupSynchronization::createGroup : groupSync uri - " << groupSyncUri
+//                << ", type - " << collectionResourceType << endl;
+
+        result = OCPlatform::registerResource(groupSyncResHandle, groupSyncUri,
+                groupSyncResType, resourceInterface,
+                std::bind(&GroupSynchronization::groupEntityHandler, this,
+                        std::placeholders::_1), OC_DISCOVERABLE | OC_OBSERVABLE);
+        if (result != OC_STACK_OK)
+        {
+            cout << "To register resource (groupsync) was unsuccessful. result - " << result
+                    << endl;
+            goto Error;
+        }
+
+        groupSyncResourceHandleList[collectionResourceType] = groupSyncResHandle;
+
+        return OC_STACK_OK;
+    }
+    else
+    {
+        cout << "GroupSynchronization::createGroup : Error! Input params are wrong." << endl;
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    Error:
+
+    if (collectionResHandle)
+    {
+        OCPlatform::unregisterResource(collectionResHandle);
+        auto iterator = collectionResourceHandleList.find(collectionResourceType);
+        if (iterator != collectionResourceHandleList.end())
+        {
+            collectionResourceHandleList.erase(iterator);
+        }
+    }
+
+    if (groupSyncResHandle)
+    {
+        OCPlatform::unregisterResource(groupSyncResHandle);
+        auto iterator = groupSyncResourceHandleList.find(collectionResourceType);
+        if (iterator != groupSyncResourceHandleList.end())
+        {
+            groupSyncResourceHandleList.erase(iterator);
+        }
+    }
+
+    return OC_STACK_NO_RESOURCE;
+}
+
+OCStackResult GroupSynchronization::joinGroup(std::string collectionResourceType,
+        OCResourceHandle resourceHandle)
+{
+    if ((0 != collectionResourceType.length()) && (resourceHandle))
+    {
+        auto resIt = collectionResourceHandleList.find(collectionResourceType);
+        if (resIt == groupSyncResourceHandleList.end())
+        {
+            cout << "GroupSynchronization::joinGroup : error! There is no collection to join"
+                    << endl;
+            return OC_STACK_INVALID_PARAM;
+        }
+
+        OCResourceHandle collectionResHandle = resIt->second;
+
+        OCStackResult result = OCPlatform::bindResource(collectionResHandle, resourceHandle);
+        if (result != OC_STACK_OK)
+        {
+            cout << "GroupSynchronization::joinGroup : To bind resource was unsuccessful."
+                    << "result - " << result << endl;
+            return OC_STACK_ERROR;
+        }
+        cout << "GroupSynchronization::joinGroup : "
+                << "To bind collectionResHandle and resourceHandle" << endl;
+
+        std::vector< OCResourceHandle > childHandleList;
+
+        auto childIt = childResourceHandleList.find(collectionResHandle);
+        if (childIt != childResourceHandleList.end())
+        {
+            childHandleList = childIt->second;
+        }
+
+        childHandleList.push_back(resourceHandle);
+        childResourceHandleList[collectionResHandle] = childHandleList;
+
+        deviceResourceHandleList.push_back(resourceHandle);
+
+        debugGroupSync();
+    }
+    else
+    {
+        cout << "GroupSynchronization::joinGroup : Error! input params are wrong." << endl;
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OC_STACK_OK;
+}
+
+OCStackResult GroupSynchronization::joinGroup(const std::shared_ptr< OCResource > resource,
+        OCResourceHandle resourceHandle)
+{
+    if ((resource) && (resourceHandle))
+    {
+        cout << "GroupSynchronization::joinGroup" << endl;
+
+        // making representation to join group
+        std::string method = "joinGroup";
+        std::vector< std::string > type = resource->getResourceTypes();
+        std::string resourceType;
+        resourceType.append(OCGetResourceTypeName(resourceHandle, 0));
+
+        OCRepresentation rep;
+        rep.setValue("method", method);
+        rep.setValue("collectionResourceType", type[0]);
+        rep.setValue("resourceType", resourceType);
+
+        cout << "\tmethod - " << method << endl;
+        cout << "\tcollectionResourceType - " << type[0] << endl;
+        cout << "\tresourceType - " << resourceType << endl;
+
+        // creating group sync resource with the received collection resource.
+        // entity handler of group sync is used to join group.
+        std::string host = resource->host();
+        std::string uri = resource->uri() + "/groupsync";
+
+        std::vector< std::string > resourceTypes;
+        std::string temp;
+        for (unsigned int i = 0; i < type.size(); ++i)
+        {
+            temp = type[0] + ".groupsync";
+            resourceTypes.push_back(temp);
+        }
+
+        std::vector< std::string > resourceInterface;
+        resourceInterface.push_back(DEFAULT_INTERFACE);
+
+        OCResource::Ptr groupSyncResource = OCPlatform::constructResourceObject(host, uri, 1,
+                resourceTypes, resourceInterface);
+        groupSyncResourceList[type[0]] = groupSyncResource;
+
+        cout << "GroupSynchronization::joinGroup : creating groupSyncResource." << endl;
+
+        // Create QueryParameters Map and add query params (if any)
+        QueryParamsMap queryParamsMap;
+
+        // request to join group to the remote group sync resource
+        OCStackResult result = groupSyncResource->put(rep, queryParamsMap,
+                std::bind(&GroupSynchronization::onJoinGroup, this, std::placeholders::_1,
+                        std::placeholders::_2, std::placeholders::_3));
+        if (OC_STACK_OK == result)
+        {
+            cout << "GroupSynchronization::joinGroup : groupSyncResource->put was successful."
+                    << endl;
+        }
+        else
+        {
+            cout << "GroupSynchronization::joinGroup : "
+                    << "groupSyncResource->put was unsuccessful. result - " << result << endl;
+        }
+
+        // saving the remote collection resource.
+        // It is used in onJoinGroup() and onGetJoinedRemoteChild().
+        remoteCollectionResource = resource;
+
+        // saving the resource handle to join. It is used in onGetJoinedRemoteChild()
+        deviceResourceHandle = resourceHandle;
+
+        return OC_STACK_OK;
+    }
+    else
+    {
+        cout << "GroupSynchronization::joinGroup : Error! Input params are wrong." << endl;
+        return OC_STACK_INVALID_PARAM;
+    }
+}
+
+OCStackResult GroupSynchronization::leaveGroup(std::string collectionResourceType,
+        OCResourceHandle resourceHandle)
+{
+    if ((0 != collectionResourceType.length()) && (resourceHandle))
+    {
+        cout << "GroupSynchronization::leaveGroup : collectionResourceType - "
+                << collectionResourceType << endl;
+
+        OCResourceHandle collectionResHandle;
+
+        auto handleIt = groupSyncResourceHandleList.find(collectionResourceType);
+
+        // if groupSyncResourceHandleList has resourceType,
+        // this app created collection resource handle.
+        if (handleIt != groupSyncResourceHandleList.end())
+        {
+            handleIt = collectionResourceHandleList.find(collectionResourceType);
+            if (handleIt == collectionResourceHandleList.end())
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "Error! There is no collection resource handle to leave." << endl;
+                return OC_STACK_INVALID_PARAM;
+            }
+
+            collectionResHandle = handleIt->second;
+//            cout << "GroupSynchronization::leaveGroup : collection handle uri - "
+//                    << OCGetResourceUri(collectionResHandle) << endl;
+
+            OCStackResult result = OCPlatform::unbindResource(collectionResHandle,
+                    resourceHandle);
+            if (OC_STACK_OK == result)
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "To unbind resource was successful." << endl;
+            }
+            else
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "To unbind resource was unsuccessful. result - " << result << endl;
+            }
+
+            auto It = std::find(deviceResourceHandleList.begin(),
+                    deviceResourceHandleList.end(), resourceHandle);
+            if (It == deviceResourceHandleList.end()) // there is no resource handle to find
+            {
+                result = OCPlatform::unregisterResource(resourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "GroupSynchronization::leaveGroup : "
+                            << "To unregister resource was successful." << endl;
+                }
+                else
+                {
+                    cout << "GroupSynchronization::leaveGroup : "
+                            << "To unregister resource was unsuccessful. result - " << result
+                            << endl;
+                }
+            }
+            else
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "This resource cannot be unregistered." << endl;
+                deviceResourceHandleList.erase(It);
+            }
+
+            auto handleListIt = childResourceHandleList.find(collectionResHandle);
+            if (handleListIt == childResourceHandleList.end())
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "Error! There is no child resource list to delete." << endl;
+                return OC_STACK_INVALID_PARAM;
+            }
+
+            std::vector< OCResourceHandle > childList = handleListIt->second;
+            auto childIt = std::find(childList.begin(), childList.end(), resourceHandle);
+            if (childIt != childList.end())
+            {
+                cout << "GroupSynchronization::groupEntityHandler : "
+                        << "Found! The resource to leave is found." << endl;
+                childList.erase(childIt);
+            }
+
+            childResourceHandleList[collectionResHandle] = childList;
+
+            debugGroupSync();
+        }
+        else // requesting to unbind this resourceHandle to the remote collection resource
+        {
+            auto resourceIt = groupSyncResourceList.find(collectionResourceType);
+
+            if (resourceIt == groupSyncResourceList.end())
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "Error! There is no collectin resource type to leave." << endl;
+                return OC_STACK_INVALID_PARAM;
+            }
+
+            std::shared_ptr< OCResource > resource = resourceIt->second;
+//            cout << "GroupSynchronization::leaveGroup : group sync resource uri - "
+//                    << resource->uri() << endl;
+
+            handleIt = collectionResourceHandleList.find(collectionResourceType);
+            if (handleIt == collectionResourceHandleList.end())
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "Error! There is no collection resource handle to leave." << endl;
+                return OC_STACK_INVALID_PARAM;
+            }
+
+            collectionResHandle = handleIt->second;
+
+            // making representation to leave group
+            std::string method = "leaveGroup";
+            std::string type = OCGetResourceTypeName(collectionResHandle, 0);
+            std::string resourceType;
+            resourceType.append(OCGetResourceTypeName(resourceHandle, 0));
+
+            OCRepresentation rep;
+            rep.setValue("method", method);
+            rep.setValue("collectionResourceType", type);
+            rep.setValue("resourceType", resourceType);
+
+            cout << "\tmethod - " << method << endl;
+            cout << "\tcollectionResourceType - " << type << endl;
+            cout << "\tresourceType - " << resourceType << endl;
+
+            QueryParamsMap queryParamsMap;
+
+            // request to leave group to the remote group sync resource
+            OCStackResult result = resource->put(rep, queryParamsMap,
+                    std::bind(&GroupSynchronization::onLeaveGroup, this, std::placeholders::_1,
+                            std::placeholders::_2, std::placeholders::_3));
+            if (OC_STACK_OK == result)
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "groupSyncResource->put was successful." << endl;
+            }
+            else
+            {
+                cout << "GroupSynchronization::leaveGroup : "
+                        << "groupSyncResource->put was unsuccessful. result - " << result
+                        << endl;
+            }
+
+            // deleting all remote resources. These are copied in onGetJoinedRemoteChild()
+            deleteGroup(collectionResourceType);
+        }
+    }
+    else
+    {
+        cout << "GroupSynchronization::leaveGroup : Error! Input params are wrong." << endl;
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OC_STACK_OK;
+}
+
+void GroupSynchronization::deleteGroup(std::string collectionResourceType)
+{
+    if (0 != collectionResourceType.length())
+    {
+        cout << "GroupSynchronization::deleteGroup" << endl;
+
+        OCStackResult result;
+
+        auto handleIt = collectionResourceHandleList.find(collectionResourceType);
+        if (handleIt == collectionResourceHandleList.end())
+        {
+            cout << "GroupSynchronization::deleteGroup : "
+                    << "Error! There is no collection resource handle to delete." << endl;
+            return;
+        }
+        OCResourceHandle collectionResHandle = handleIt->second;
+
+        collectionResourceHandleList.erase(handleIt);
+
+        auto handleListIt = childResourceHandleList.find(collectionResHandle);
+        if (handleListIt == childResourceHandleList.end())
+        {
+            cout << "GroupSynchronization::deleteGroup : "
+                    << "Error! There is no child resource list to delete." << endl;
+            return;
+        }
+        std::vector< OCResourceHandle > childList = handleListIt->second;
+
+        childResourceHandleList.erase(handleListIt);
+
+        result = OCPlatform::unbindResources(collectionResHandle, childList);
+        if (OC_STACK_OK == result)
+        {
+            cout << "GroupSynchronization::deleteGroup : "
+                    << "To unbind resources was successful." << endl;
+        }
+        else
+        {
+            cout << "GroupSynchronization::deleteGroup : "
+                    << "To unbind resources was unsuccessful. result - " << result << endl;
+        }
+
+        result = OCPlatform::unregisterResource(collectionResHandle);
+        if (result != OC_STACK_OK)
+        {
+            cout << "GroupSynchronization::deleteGroup : "
+                    << "To unregister collection resource handle was successful." << endl;
+        }
+        else
+        {
+            cout << "GroupSynchronization::deleteGroup : "
+                    << " To unregister collection resource handle was unsuccessful. result - "
+                    << result << endl;
+        }
+
+        OCResourceHandle resourceHandle;
+        std::vector< OCResourceHandle >::iterator It;
+
+        for (unsigned int i = 0; i < childList.size(); i++)
+        {
+            resourceHandle = childList.at(i);
+
+            It = std::find(deviceResourceHandleList.begin(), deviceResourceHandleList.end(),
+                    resourceHandle);
+            if (It != deviceResourceHandleList.end()) // find !!
+            {
+                deviceResourceHandleList.erase(It);
+            }
+            else
+            {
+                result = OCPlatform::unregisterResource(resourceHandle);
+                if (OC_STACK_OK == result)
+                {
+                    cout << "GroupSynchronization::deleteGroup : UnregisterResource(" << i + 1
+                            << ") was successful." << endl;
+                }
+                else
+                {
+                    cout << "GroupSynchronization::deleteGroup : UnregisterResource(" << i + 1
+                            << ") was unsuccessful. result - " << result << endl;
+                }
+            }
+        }
+
+        handleIt = groupSyncResourceHandleList.find(collectionResourceType);
+
+        // if groupSyncResourceHandleList has resourceType,
+        // group sync of this app created collection resource.
+        if (handleIt != groupSyncResourceHandleList.end())
+        {
+            resourceHandle = handleIt->second; // group sync resource handle
+            result = OCPlatform::unregisterResource(resourceHandle);
+            if (OC_STACK_OK == result)
+            {
+                cout << "GroupSynchronization::deleteGroup : "
+                        << "To unregister group sync resource handle was successful." << endl;
+            }
+            else
+            {
+                cout << "GroupSynchronization::deleteGroup : "
+                        << "To unregister group sync resource handle was unsuccessful. "
+                        << "result - " << result << endl;
+            }
+
+            groupSyncResourceHandleList.erase(handleIt);
+        }
+
+        auto resourceIt = groupSyncResourceList.find(collectionResourceType);
+        if (resourceIt != groupSyncResourceList.end())
+        {
+            groupSyncResourceList.erase(resourceIt);
+        }
+
+        debugGroupSync();
+    }
+    else
+    {
+        cout << "GroupSynchronization::deleteGroup : Error! Input params are wrong." << endl;
+    }
+}
+
+std::map< std::string, OCResourceHandle > GroupSynchronization::getGroupList()
+{
+    return collectionResourceHandleList;
+}
+
+OCEntityHandlerResult GroupSynchronization::groupEntityHandler(
+        const std::shared_ptr< OCResourceRequest > request)
+{
+    cout << "GroupSynchronization::groupEntityHandler\n";
+
+    if (request)
+    {
+        // Get the request type and request flag
+        std::string requestType = request->getRequestType();
+        int requestFlag = request->getRequestHandlerFlag();
+
+        if (requestFlag == RequestHandlerFlag::InitFlag)
+        {
+            cout << "\trequestFlag : Init\n";
+
+            // entity handler to perform resource initialization operations
+        }
+        else if (requestFlag == RequestHandlerFlag::RequestFlag)
+        {
+            cout << "\trequestFlag : Request\n";
+
+            // If the request type is GET
+            if (requestType == "GET")
+            {
+                cout << "\t\trequestType : GET\n";
+            }
+            else if (requestType == "PUT")
+            {
+                cout << "\t\trequestType : PUT\n";
+
+                //get method name, group resource type and resource type to join group
+                OCRepresentation rp = request->getResourceRepresentation();
+                std::string methodType = rp.getValue< std::string >("method");
+                std::string collectionResourceType = rp.getValue< std::string >(
+                        "collectionResourceType");
+                std::string resourceType = rp.getValue< std::string >("resourceType");
+
+                cout << "\t\t\tmethod : " << methodType << endl;
+                cout << "\t\t\tcollection resourceType : " << collectionResourceType << endl;
+                cout << "\t\t\tresourceType : " << resourceType << endl;
+
+                auto handleIt = collectionResourceHandleList.find(collectionResourceType);
+                if (handleIt == collectionResourceHandleList.end())
+                {
+                    cout << "GroupSynchronization::groupEntityHandler : "
+                            << "Error! There is no collection resource handle to delete."
+                            << endl;
+                    return OC_EH_ERROR;
+                }
+                collectionResourceHandle = handleIt->second;
+                // in case of join group it is used in onFindResource()
+
+                if (methodType == "joinGroup")
+                {
+                    std::string resourceName = "coap://224.0.1.187/oc/core?rt=";
+                    resourceName += resourceType;
+                    cout << "\t\t\tresourceName : " << resourceName << endl;
+
+                    resourceRequest = request;
+
+                    OCPlatform::findResource("", resourceName,
+                            std::bind(&GroupSynchronization::onFindResource, this,
+                                    std::placeholders::_1));
+                }
+                else if (methodType == "leaveGroup")
+                {
+                    auto it = childResourceHandleList.find(collectionResourceHandle);
+                    if (it == childResourceHandleList.end())
+                    {
+                        cout << "GroupSynchronization::groupEntityHandler : "
+                                << "Error! There is no child resource list." << endl;
+                        return OC_EH_ERROR;
+                    }
+
+                    std::vector< OCResourceHandle > childList = it->second;
+                    OCResourceHandle resourceHandle;
+                    for (auto childIt = childList.begin(); childIt != childList.end();)
+                    {
+                        resourceHandle = (*childIt);
+                        char* type = (char*) OCGetResourceTypeName(resourceHandle, 0);
+
+                        if (0 == resourceType.compare(type))
+                        {
+                            cout << "GroupSynchronization::groupEntityHandler : "
+                                    << "Found! The resource to leave is found. - " << type
+                                    << endl;
+
+                            childIt = childList.erase(childIt++);
+
+                            OCStackResult result = OCPlatform::unbindResource(
+                                    collectionResourceHandle, resourceHandle);
+                            if (OC_STACK_OK == result)
+                            {
+                                cout << "GroupSynchronization::groupEntityHandler : "
+                                        << "To unbind resource was successful." << endl;
+                            }
+                            else
+                            {
+                                cout << "GroupSynchronization::groupEntityHandler : "
+                                        << "To unbind resource was unsuccessful. result - "
+                                        << result << endl;
+                            }
+
+                            result = OCPlatform::unregisterResource(resourceHandle);
+                            if (OC_STACK_OK == result)
+                            {
+                                cout << "GroupSynchronization::groupEntityHandler : "
+                                        << "To unregister resource was successful." << endl;
+                            }
+                            else
+                            {
+                                cout << "GroupSynchronization::groupEntityHandler : "
+                                        << "To unregister resource was unsuccessful. result - "
+                                        << result << endl;
+                            }
+
+//                            break;
+                        }
+                        else
+                        {
+                            ++childIt;
+                        }
+
+                    }
+
+                    childResourceHandleList[collectionResourceHandle] = childList;
+
+                    debugGroupSync();
+
+                    auto pResponse = std::make_shared< OC::OCResourceResponse >();
+                    pResponse->setRequestHandle(request->getRequestHandle());
+                    pResponse->setResourceHandle(request->getResourceHandle());
+                    pResponse->setErrorCode(200);
+                    pResponse->setResponseResult(OC_EH_OK);
+
+                    OCRepresentation rep = request->getResourceRepresentation();
+                    pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+                    if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+                    {
+                        cout << "GroupSynchronization::groupEntityHandler : "
+                                << "sendResponse is successful." << endl;
+                    }
+                }
+
+                if (methodType != "") //TODO: Check groupmethodtype NULL
+                {
+                }
+            }
+            else if (requestType == "POST")
+            {
+                // POST request operations
+            }
+            else if (requestType == "DELETE")
+            {
+                // DELETE request operations
+            }
+        }
+        else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+        {
+            cout << "\trequestFlag : Observer\n";
+        }
+    }
+    else
+    {
+        std::cout << "Request invalid" << std::endl;
+    }
+
+    return OC_EH_OK;
+}
+
+void GroupSynchronization::onFindGroup(std::shared_ptr< OCResource > resource)
+{
+    cout << "GroupSynchronization::onFindGroup" << endl;
+
+    try
+    {
+        if (resource)
+        {
+//////////////////////////////////////////////////////////////////////////////////////////////////
+////////////debugging
+            std::string resourceURI;
+            std::string hostAddress;
+
+            // Get the resource URI
+            resourceURI = resource->uri();
+            cout << "\tURI of the resource: " << resourceURI << endl;
+
+            // Get the resource host address
+            hostAddress = resource->host();
+            cout << "\tHost address of the resource: " << hostAddress << endl;
+
+            hostAddress.append(resourceURI);
+
+            // Get the resource types
+            cout << "\tList of resource types: " << endl;
+
+            for (auto &resourceTypes : resource->getResourceTypes())
+            {
+                cout << "\t\t" << resourceTypes << endl;
+            }
+
+            // Get the resource interfaces
+            cout << "\tList of resource interfaces: " << endl;
+            for (auto &resourceInterfaces : resource->getResourceInterfaces())
+            {
+                cout << "\t\t" << resourceInterfaces << endl;
+            }
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+            if (false == IsSameGroup(resource))
+            {
+                saveGroup(resource);
+                findCallback(resource);
+            }
+        }
+        else
+        {
+            // Resource is invalid
+            cout << "Resource is invalid" << endl;
+            findCallback(NULL);
+        }
+
+    }
+    catch (std::exception& e)
+    {
+        //log(e.what());
+    }
+}
+
+void GroupSynchronization::checkFindGroup(void)
+{
+    cout << "GroupSynchronization::checkFindGroup" << endl;
+
+    for (int i = 0; i < 15; i++)
+    {
+        std::chrono::milliseconds workTime(300);
+        std::this_thread::sleep_for(workTime);
+
+        std::lock_guard < std::mutex > guard(foundGroupMutex);
+
+        if (false == foundGroupResourceList.empty())
+        {
+            cout << "GroupSynchronization::checkFoundGroup : " << "Some group is received."
+                    << endl;
+            return;
+        }
+    }
+
+    cout << "GroupSynchronization::checkFoundGroup : "
+            << "It is failed to find resource within 3s." << endl;
+
+    onFindGroup(NULL);
+    return;
+}
+
+bool GroupSynchronization::IsSameGroup(std::shared_ptr< OCResource > resource)
+{
+    std::lock_guard < std::mutex > guard(foundGroupMutex);
+
+    if (true == foundGroupResourceList.empty())
+    {
+        cout << "GroupSynchronization::IsSameGroup : There is no found group." << endl;
+        return false;
+    }
+
+    std::string foundHostAddress, savedHostAddress;
+    foundHostAddress = resource->host();
+//    foundHostAddress.append (resource->uri());
+
+    for (unsigned int i = 0; i < foundGroupResourceList.size(); ++i)
+    {
+        savedHostAddress = (foundGroupResourceList.at(i))->host();
+//        savedHostAddress.append ((foundGroupResourceList.at(i))->uri());
+//        cout << "GroupSynchronization::IsSameGroup : foundHostAddress - " << foundHostAddress
+//                << ", savedHostAddress - " << savedHostAddress << endl;
+
+        if (0 == foundHostAddress.compare(savedHostAddress.c_str()))
+        {
+            cout << "GroupSynchronization::IsSameGroup : Found! The same group is found."
+                    << endl;
+            return true;
+        }
+    }
+
+    cout << "GroupSynchronization::IsSameGroup :  There is no same group." << endl;
+    return false;
+}
+
+void GroupSynchronization::saveGroup(std::shared_ptr< OCResource > resource)
+{
+    cout << "GroupSynchronization::saveGroup" << endl;
+
+    std::lock_guard < std::mutex > guard(foundGroupMutex);
+
+    foundGroupResourceList.push_back(resource);
+}
+
+void GroupSynchronization::onJoinGroup(const HeaderOptions& headerOptions,
+        const OCRepresentation& rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        cout << "GroupSynchronization::onJoinGroup : " << endl;
+
+        if (remoteCollectionResource)
+        {
+            std::string resourceInterface = DEFAULT_INTERFACE;
+            QueryParamsMap queryParamsMap;
+
+            OCStackResult result = remoteCollectionResource->get("", resourceInterface,
+                    queryParamsMap,
+                    std::bind(&GroupSynchronization::onGetJoinedRemoteChild, this,
+                            std::placeholders::_1, std::placeholders::_2,
+                            std::placeholders::_3));
+            if (OC_STACK_OK == result)
+            {
+                cout << "GroupSynchronization::onJoinGroup : "
+                        << "remoteCollectionResource->get was successful." << endl;
+            }
+            else
+            {
+                cout << "GroupSynchronization::onJoinGroup : "
+                        << "remoteCollectionResource->get was unsuccessful. result - " << result
+                        << endl;
+            }
+        }
+    }
+    else
+    {
+        cout << "GroupSynchronization::onJoinGroup : error - " << eCode << endl;
+    }
+}
+
+void GroupSynchronization::onFindResource(std::shared_ptr< OCResource > resource)
+{
+    cout << "GroupSynchronization::onFindResource" << endl;
+
+    if (resource)
+    {
+//////////////////////////////////////////////////////////////////////////////////////////////////
+////////// debugging
+        std::string resourceURI;
+        std::string hostAddress;
+
+        // Get the resource URI
+        resourceURI = resource->uri();
+        cout << "\tURI of the resource: " << resourceURI << endl;
+
+        // Get the resource host address
+        hostAddress = resource->host();
+        cout << "\tHost address of the resource: " << hostAddress << endl;
+
+        hostAddress.append(resourceURI);
+
+        // Get the resource types
+        cout << "\tList of resource types: " << endl;
+
+        for (auto &resourceTypes : resource->getResourceTypes())
+        {
+            cout << "\t\t" << resourceTypes << endl;
+        }
+
+        // Get the resource interfaces
+        cout << "\tList of resource interfaces: " << endl;
+        for (auto &resourceInterfaces : resource->getResourceInterfaces())
+        {
+            cout << "\t\t" << resourceInterfaces << endl;
+        }
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+        OCResourceHandle resourceHandle;
+        OCStackResult result = OCPlatform::registerResource(resourceHandle, resource);
+        if (result != OC_STACK_OK)
+        {
+            cout << "GroupSynchronization::"
+                    << "onFindResource - Resource to join creation was unsuccessful. result - "
+                    << result << endl;
+            return;
+        }
+//        cout << "GroupSynchronization::onFindResource : creating resourceHandle. resource type - "
+//                << OCGetResourceTypeName(resourceHandle, 0) << endl;
+
+        result = OCPlatform::bindResource(collectionResourceHandle, resourceHandle);
+        if (result != OC_STACK_OK)
+        {
+            cout << "GroupSynchronization::onFindResource : "
+                    << "To bind resource was unsuccessful. result - " << result << endl;
+            return;
+        }
+        cout << "GroupSynchronization::onFindResource : "
+                << "To bind joinGroupHandle and resourceHandle was successful." << endl;
+
+        auto it = childResourceHandleList.find(collectionResourceHandle);
+        std::vector< OCResourceHandle > childHandleList;
+        if (it != childResourceHandleList.end())
+        {
+            childHandleList = it->second;
+        }
+
+        childHandleList.push_back(resourceHandle);
+        childResourceHandleList[collectionResourceHandle] = childHandleList;
+
+        auto pResponse = std::make_shared< OC::OCResourceResponse >();
+        pResponse->setRequestHandle(resourceRequest->getRequestHandle());
+        pResponse->setResourceHandle(resourceRequest->getResourceHandle());
+        pResponse->setErrorCode(200);
+        pResponse->setResponseResult(OC_EH_OK);
+
+        OCRepresentation rep = resourceRequest->getResourceRepresentation();
+        pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+        if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+        {
+            cout << "GroupSynchronization::onFindResource : sendResponse is successful."
+                    << endl;
+        }
+    }
+    else
+    {
+        cout << "GroupSynchronization::onFindResource : "
+                << "Resource is invalid. So a new Group Resource has to be created." << endl;
+    }
+
+    debugGroupSync();
+}
+
+void GroupSynchronization::onGetJoinedRemoteChild(const HeaderOptions& headerOptions,
+        const OCRepresentation& rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        cout << "GroupSynchronization::onGetJoinedRemoteChild" << endl;
+
+//////////////////////////////////////////////////////////////////////////////////////////////////
+////////// debugging
+        std::string resourceURI;
+
+        // Get the resource URI
+        resourceURI = rep.getUri();
+        cout << "\tURI of the resource: " << resourceURI << endl;
+
+        // Get the resource types
+        cout << "\tList of resource types: " << endl;
+
+        for (auto &resourceTypes : rep.getResourceTypes())
+        {
+            cout << "\t\t" << resourceTypes << endl;
+        }
+
+        // Get the resource interfaces
+        cout << "\tList of resource interfaces: " << endl;
+        for (auto &resourceInterfaces : rep.getResourceInterfaces())
+        {
+            cout << "\t\t" << resourceInterfaces << endl;
+        }
+
+        std::vector< OCRepresentation > childList = rep.getChildren();
+        OCRepresentation child;
+        for (unsigned int i = 0; i < childList.size(); ++i)
+        {
+            cout << "\n\tchild resource - " << i + 1 << endl;
+
+            child = childList.at(i);
+            resourceURI = child.getUri();
+            cout << "\t\tURI of the resource: " << resourceURI << endl;
+
+            cout << "\t\tList of resource types: " << endl;
+            for (auto &types : child.getResourceTypes())
+            {
+                cout << "\t\t\t" << types << endl;
+            }
+
+            cout << "\tList of resource interfaces: " << endl;
+            for (auto &interfaces : child.getResourceInterfaces())
+            {
+                cout << "\t\t\t" << interfaces << endl;
+            }
+        }
+//////////////////////////////////////////////////////////////////////////////////////////////////
+
+        // creating remote collection resource handle
+        OCResourceHandle remoteCollectionResourceHandle;
+        resourceURI = remoteCollectionResource->uri();
+        std::vector< std::string > types = remoteCollectionResource->getResourceTypes();
+        std::vector< std::string > interfaces =
+                remoteCollectionResource->getResourceInterfaces();
+
+        OCStackResult result = OCPlatform::registerResource(remoteCollectionResourceHandle,
+                resourceURI, types[0], interfaces[0], NULL, OC_OBSERVABLE);
+        if (result != OC_STACK_OK)
+        {
+            cout << "GroupSynchronization::onGetJoinedRemoteChild - "
+                    << "To register remoteCollectionResourceHandle"
+                    << " was unsuccessful. result - " << result << endl;
+            return;
+        }
+        cout << "GroupSynchronization::onGetJoinedRemoteChild : "
+                "To register remoteCollectionResourceHandle was successful." << endl;
+
+        // binding remote collection resource handle and resource handle to join
+        collectionResourceHandleList[types[0]] = remoteCollectionResourceHandle;
+
+        result = OCPlatform::bindResource(remoteCollectionResourceHandle, deviceResourceHandle);
+        if (OC_STACK_OK == result)
+        {
+            cout << "GroupSynchronization::onGetJoinedRemoteChild : "
+                    << "binding remoteCollectionResourceHandle and deviceResourceHandle"
+                    << endl;
+        }
+        else
+        {
+            cout << "GroupSynchronization::onGetJoinedRemoteChild - "
+                    << "To bind remoteCollectionResourceHandle and deviceResourceHandle "
+                    << "was unsuccessful. result - " << result << endl;
+        }
+
+        std::vector< OCResourceHandle > childHandleList;
+        childHandleList.push_back(deviceResourceHandle);
+        deviceResourceHandleList.push_back(deviceResourceHandle);
+
+        // binding copied remote collection resource handle and copied remote resource
+        OCResourceHandle resourceHandle;
+        for (unsigned int i = 0; i < childList.size(); ++i)
+        {
+            cout << "\tremote resource - " << i + 1 << endl;
+
+            child = childList.at(i);
+            resourceURI = child.getUri();
+            types = child.getResourceTypes();
+            interfaces = child.getResourceInterfaces();
+
+            if (0 == types[0].compare(OCGetResourceTypeName(deviceResourceHandle, 0)))
+            {
+                cout << "GroupSynchronization::onGetJoinedRemoteChild : " << types[0]
+                        << " is bind already." << endl;
+                continue;
+            }
+
+            result = OCPlatform::registerResource(resourceHandle, resourceURI, types[0],
+                    interfaces[0], NULL, OC_OBSERVABLE);
+            if (OC_STACK_OK == result)
+            {
+                result = OCPlatform::bindResource(remoteCollectionResourceHandle,
+                        resourceHandle);
+                if (result != OC_STACK_OK)
+                {
+                    cout << "GroupSynchronization::onGetJoinedRemoteChild - "
+                            << "binding remoteCollectionResourceHandle and resourceHandle "
+                            << "was unsuccessful. result - " << result << endl;
+                    OCPlatform::unregisterResource(resourceHandle);
+                }
+
+                childHandleList.push_back(resourceHandle);
+                cout << "GroupSynchronization::onGetJoinedRemoteChild : "
+                        << "binding remoteCollectionResourceHandle and resourceHandle" << endl;
+            }
+            else
+            {
+                cout << "GroupSynchronization::onGetJoinedRemoteChild - "
+                        << "To register remoteCollectionResourceHandle was unsuccessful."
+                        << " result - " << result << endl;
+            }
+        }
+
+        childResourceHandleList[remoteCollectionResourceHandle] = childHandleList;
+        // this handle list is used to leave group
+    }
+    else
+    {
+        cout << "GroupSynchronization::onGetJoinedRemoteChild : error - " << eCode << endl;
+    }
+
+    debugGroupSync();
+}
+
+void GroupSynchronization::onLeaveGroup(const HeaderOptions& headerOptions,
+        const OCRepresentation& rep, const int eCode)
+{
+    if (eCode == OC_STACK_OK)
+    {
+        cout << "GroupSynchronization::onLeaveGroup" << endl;
+    }
+    else
+    {
+        cout << "GroupSynchronization::onLeaveGroup : error - " << eCode << endl;
+    }
+    debugGroupSync();
+}
+
+void GroupSynchronization::debugGroupSync(void)
+{
+    cout << "GroupSynchronization::debugGroupSync" << endl;
+
+    unsigned int i;
+    std::map< std::string, OCResourceHandle >::iterator handleIt;
+    std::map< OCResourceHandle, std::vector< OCResourceHandle > >::iterator childIt;
+    std::string type;
+    OCResourceHandle resourceHandle;
+    std::vector< OCResourceHandle > handleList;
+    std::shared_ptr< OCResource > resource;
+
+    cout << "Resource Handle Created by App" << endl;
+    for (i = 0; i < deviceResourceHandleList.size(); i++)
+    {
+        resourceHandle = deviceResourceHandleList.at(i);
+
+        cout << i + 1 << ". details" << endl;
+        cout << "  uri - " << OCGetResourceUri(resourceHandle) << endl;
+        cout << "  resource type - " << OCGetResourceTypeName(resourceHandle, 0) << endl;
+        cout << "  resource interface - " << OCGetResourceInterfaceName(resourceHandle, 0)
+                << endl << endl;
+    }
+
+    cout << "\nGroup Sync Resource Handle List. The number is "
+            << groupSyncResourceHandleList.size() << endl;
+    i = 1;
+    for (handleIt = groupSyncResourceHandleList.begin();
+            handleIt != groupSyncResourceHandleList.end(); ++handleIt)
+    {
+        type = handleIt->first;
+        cout << "\t" << i << ". group sync resource type - " << type << endl;
+        cout << "\t  details" << endl;
+
+        resourceHandle = handleIt->second;
+        cout << "\t  uri - " << OCGetResourceUri(resourceHandle) << endl;
+        cout << "\t  resource type - " << OCGetResourceTypeName(resourceHandle, 0) << endl;
+        cout << "\t  resource interface - " << OCGetResourceInterfaceName(resourceHandle, 0)
+                << endl << endl;
+        ;
+        i++;
+    }
+
+    cout << "Copied Remote Group Sync Resource List. The number is "
+            << groupSyncResourceList.size() << endl;
+    std::vector< std::string > list;
+    i = 1;
+    for (auto resourceIt = groupSyncResourceList.begin();
+            resourceIt != groupSyncResourceList.end(); ++resourceIt)
+    {
+        type = resourceIt->first;
+        cout << "\t" << i << ". group sync resource type - " << type << endl;
+        cout << "\t details" << endl;
+
+        resource = resourceIt->second;
+        cout << "\t  host - " << resource->host() << endl;
+        cout << "\t  uri - " << resource->uri() << endl;
+        list = resource->getResourceTypes();
+        cout << "\t  resource type - " << list[0] << endl;
+        list = resource->getResourceInterfaces();
+        cout << "\t  resource interface - " << list[0] << endl << endl;
+        i++;
+    }
+
+//    cout << "The number of collection Resource Handle is " << collectionResourceHandleList.size()
+//            << endl;
+//    cout << "The number of child resource handle list is " << childResourceHandleList.size()
+//            << endl;
+
+    cout << "Collection Resource Handle List" << endl;
+    i = 1;
+    for (handleIt = collectionResourceHandleList.begin();
+            handleIt != collectionResourceHandleList.end(); ++handleIt)
+    {
+        type = handleIt->first;
+        cout << "\t" << i << ". collection resource type - " << type << endl;
+        cout << "\t  details" << endl;
+
+        resourceHandle = handleIt->second;
+        cout << "\t  uri - " << OCGetResourceUri(resourceHandle) << endl;
+        cout << "\t  resource type - " << OCGetResourceTypeName(resourceHandle, 0) << endl;
+        cout << "\t  resource interface - " << OCGetResourceInterfaceName(resourceHandle, 0)
+                << endl << endl;
+
+        childIt = childResourceHandleList.find(resourceHandle);
+        if (childIt != childResourceHandleList.end())
+        {
+            handleList = childIt->second;
+            for (unsigned int j = 0; j < handleList.size(); j++)
+            {
+
+                cout << "\t\t" << j + 1 << ". child resource details" << endl;
+
+                resourceHandle = handleList.at(j);
+                cout << "\t\t  uri - " << OCGetResourceUri(resourceHandle) << endl;
+                cout << "\t\t  resource type - " << OCGetResourceTypeName(resourceHandle, 0)
+                        << endl;
+                cout << "\t\t  resource interface - "
+                        << OCGetResourceInterfaceName(resourceHandle, 0) << endl << endl;
+            }
+        }
+
+        i++;
+    }
+}
+}
diff --git a/service/things-manager/sdk/src/GroupSynchronization.h b/service/things-manager/sdk/src/GroupSynchronization.h
new file mode 100644 (file)
index 0000000..da5f153
--- /dev/null
@@ -0,0 +1,138 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file   GroupSynchronization.h
+
+/// @brief  This file contains the declaration of classes and
+///its members related to GroupSynchronization.
+
+#ifndef __OC_GROUPSYNCHRONIZATION__
+#define __OC_GROUPSYNCHRONIZATION__
+
+#include <string>
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+
+namespace OIC
+{
+class GroupSynchronization
+{
+private:
+
+    std::map< std::string, OCResourceHandle > collectionResourceHandleList;
+    // collection resource handle list
+    std::map< OCResourceHandle, std::vector< OCResourceHandle > > childResourceHandleList;
+
+    std::map< std::string, OCResourceHandle > groupSyncResourceHandleList;
+    // group sync resource handle list
+    std::map< std::string, std::shared_ptr< OCResource > > groupSyncResourceList;
+    // remote group sync resource list
+
+    std::vector< OCResourceHandle > deviceResourceHandleList; // these cannot be removed.
+    OCResourceHandle deviceResourceHandle;
+
+    OCResourceHandle collectionResourceHandle; // collection handle
+    std::shared_ptr< OCResource > remoteCollectionResource;
+
+    FindCallback findCallback;
+
+    std::vector< std::shared_ptr< OCResource > > foundGroupResourceList;
+
+    std::mutex foundGroupMutex;
+//    std::mutex groupSyncMutex;
+
+    std::shared_ptr< OCResourceRequest > resourceRequest; // this is used for slow response
+
+    static GroupSynchronization* groupSyncnstance;
+
+    GroupSynchronization()
+    {
+        collectionResourceHandleList.clear();
+        childResourceHandleList.clear();
+        groupSyncResourceHandleList.clear();
+        groupSyncResourceList.clear();
+        deviceResourceHandleList.clear();
+
+        deviceResourceHandle = NULL;
+        collectionResourceHandle = NULL;
+        remoteCollectionResource = NULL;
+        findCallback = NULL;
+    }
+    ;
+
+    ~GroupSynchronization()
+    {
+        std::map< std::string, OCResourceHandle >::iterator handleIt;
+        for (handleIt = collectionResourceHandleList.begin();
+                handleIt != collectionResourceHandleList.end(); ++handleIt)
+        {
+            deleteGroup(handleIt->first);
+        }
+    }
+    ;
+
+public:
+
+    static GroupSynchronization* getInstance();
+    void deleteInstance();
+
+    OCStackResult findGroup(std::vector< std::string > collectionResourceTypes,
+            FindCallback callback);
+    OCStackResult createGroup(std::string collectionResourceType);
+    OCStackResult joinGroup(std::string collectionResourceTyps,
+            OCResourceHandle resourceHandle);
+    OCStackResult joinGroup(const std::shared_ptr< OCResource > resource,
+            OCResourceHandle resourceHandle);
+    OCStackResult leaveGroup(std::string collectionResourceType,
+            OCResourceHandle resourceHandle);
+    void deleteGroup(std::string collectionResourceType);
+
+    std::map< std::string, OCResourceHandle > getGroupList();
+
+private:
+
+    OCEntityHandlerResult groupEntityHandler(
+            const std::shared_ptr< OCResourceRequest > request);
+
+    void onFindGroup(std::shared_ptr< OCResource > resource);
+    void onJoinGroup(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode);
+    void onFindResource(std::shared_ptr< OCResource > resource);
+    void onGetJoinedRemoteChild(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode);
+    void onLeaveGroup(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode);
+//    void onSubscribePresence (OCStackResult result,
+//        const unsigned int nonce/*, std::string resourceType, std::string host*/);
+
+    void checkFindGroup(void);
+    bool IsSameGroup(std::shared_ptr< OCResource > resource);
+    void saveGroup(std::shared_ptr< OCResource > resource);
+
+    void debugGroupSync(void);
+
+};
+}
+#endif    // __OC_GROUPSYNCHRONIZATION__
diff --git a/service/things-manager/sdk/src/TGMClient.cpp b/service/things-manager/sdk/src/TGMClient.cpp
deleted file mode 100644 (file)
index 7534a00..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-//******************************************************************
-//
-// Copyright 2014 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-/// @file    TGMClient.cpp
-///  @brief   
-
-#include "TGMClient.h"
-#include <algorithm>
-#include <thread>
-
-using namespace OC;
-
-std::map< std::vector< std::string >, CandidateCallback > candidateRequest;
-std::map< std::vector< std::string >, CandidateCallback > candidateRequestForTimer;
-std::map< std::string, std::map< std::string, std::shared_ptr< OCResource > > > rtForResourceList;
-std::vector< std::string > allFoundResourceTypes;
-
-template< typename T >
-bool IsSubset(std::vector< T > full, std::vector< T > sub)
-{
-    std::sort(full.begin(), full.end());
-    std::sort(sub.begin(), sub.end());
-    return std::includes(full.begin(), full.end(), sub.begin(), sub.end());
-}
-
-void TGMClient::onFoundResource(std::shared_ptr< OCResource > resource, int waitsec)
-{
-
-    std::string resourceURI;
-    std::string hostAddress;
-    try
-    {
-        // Do some operations with resource object.
-        if (resource)
-        {
-
-            std::cout << "DISCOVERED Resource:" << std::endl;
-            // Get the resource URI
-            resourceURI = resource->uri();
-            std::cout << "\tURI of the resource: " << resourceURI << std::endl;
-
-            // Get the resource host address
-            hostAddress = resource->host();
-            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;
-
-            // Get the resource types
-            std::cout << "\tList of resource types: " << std::endl;
-
-            hostAddress.append(resourceURI);
-
-            for (auto &resourceTypes : resource->getResourceTypes())
-            {
-                std::cout << "\t\t" << resourceTypes << std::endl;
-
-                if (std::find(allFoundResourceTypes.begin(), allFoundResourceTypes.end(),
-                        resourceTypes) == allFoundResourceTypes.end())
-                {
-                    allFoundResourceTypes.push_back(resourceTypes);
-                }
-
-                rtForResourceList[resourceTypes][hostAddress] = resource;
-            }
-
-            // Get the resource interfaces
-            std::cout << "\tList of resource interfaces: " << std::endl;
-            for (auto &resourceInterfaces : resource->getResourceInterfaces())
-            {
-                std::cout << "\t\t" << resourceInterfaces << std::endl;
-            }
-
-            if (waitsec == -1)
-            {
-                findPreparedRequest(candidateRequest);
-            }
-        }
-        else
-        {
-            // Resource is invalid
-            std::cout << "Resource is invalid" << std::endl;
-        }
-
-    }
-    catch (std::exception& e)
-    {
-        //log(e.what());
-    }
-}
-
-TGMClient::TGMClient(void)
-{
-    ;
-}
-
-/**
- * Virtual destructor
- */
-TGMClient::~TGMClient(void)
-{
-    candidateRequest.clear();
-    candidateRequestForTimer.clear();
-    rtForResourceList.clear();
-    allFoundResourceTypes.clear();
-}
-
-void TGMClient::findPreparedRequest(
-        std::map< std::vector< std::string >, CandidateCallback > &request)
-{
-    std::vector < std::shared_ptr < OCResource >> resources;
-
-    for (auto it = request.begin(); it != request.end();)
-    {
-
-        if (IsSubset(allFoundResourceTypes, it->first))
-        {
-            //std::cout << "IS SUBSET !!! \n";
-
-            for (unsigned int i = 0; i < it->first.size(); ++i)
-            {
-
-                for (auto secondIt = rtForResourceList[it->first.at(i)].begin();
-                        secondIt != rtForResourceList[it->first.at(i)].end(); ++secondIt)
-                {
-                    resources.push_back(secondIt->second);
-                }
-            }
-
-            it->second(resources);
-
-            //TODO : decide policy - callback only once 
-            request.erase(it++);
-        }
-        else
-        {
-            ++it;
-        }
-
-    }
-
-}
-
-void TGMClient::lazyCallback(int second)
-{
-    sleep(second);
-    findPreparedRequest(candidateRequestForTimer);
-
-}
-OCStackResult TGMClient::findCandidateResources(std::vector< std::string > resourceTypes,
-        CandidateCallback callback, int waitsec)
-{
-    if (resourceTypes.size() < 1)
-    {
-        return OC_STACK_ERROR;
-    }
-
-    std::sort(resourceTypes.begin(), resourceTypes.end());
-    resourceTypes.erase(std::unique(resourceTypes.begin(), resourceTypes.end()),
-            resourceTypes.end());
-
-    if (waitsec != -1)
-    {
-        candidateRequestForTimer.insert(std::make_pair(resourceTypes, callback));
-    }
-    else
-    {
-        candidateRequest.insert(std::make_pair(resourceTypes, callback));
-    }
-
-    for (unsigned int i = 0; i < resourceTypes.size(); ++i)
-    {
-        std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;
-        std::string query = "coap://224.0.1.187/oc/core?rt=";
-        query.append(resourceTypes.at(i));
-        OCPlatform::findResource("", query.c_str(),
-                std::function < void(std::shared_ptr < OCResource > resource)
-                        > (std::bind(&TGMClient::onFoundResource, this, std::placeholders::_1,
-                                waitsec)));
-    }
-
-    if (waitsec != -1)
-    {
-        std::thread exec(
-                std::function< void(int second) >(
-                        std::bind(&TGMClient::lazyCallback, this, std::placeholders::_1)), waitsec);
-        exec.detach();
-    }
-
-    return OC_STACK_OK;
-}
diff --git a/service/things-manager/sdk/src/ThingsConfiguration.cpp b/service/things-manager/sdk/src/ThingsConfiguration.cpp
new file mode 100644 (file)
index 0000000..a0f57a2
--- /dev/null
@@ -0,0 +1,609 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file    ThingsConfiguration.cpp
+/// @brief
+
+#include <OCApi.h>
+#include <OCPlatform.h>
+#include <cstdlib>
+#include <algorithm>
+#include "ThingsConfiguration.h"
+
+using namespace OC;
+
+namespace OIC
+{
+    const int SUCCESS_RESPONSE = 0;
+    int cnt = 0;
+
+    std::map< std::string, ConfigurationRequestEntry > configurationRequestTable;
+
+    ThingsConfiguration* ThingsConfiguration::thingsConfigurationInstance = NULL;
+
+    ConfigurationCallback g_bootstrapCallback;
+
+    ThingsConfiguration* ThingsConfiguration::getInstance()
+    {
+        if (thingsConfigurationInstance == NULL)
+        {
+            thingsConfigurationInstance = new ThingsConfiguration();
+        }
+        return thingsConfigurationInstance;
+    }
+
+    void ThingsConfiguration::deleteInstance()
+    {
+        if (thingsConfigurationInstance)
+        {
+            delete thingsConfigurationInstance;
+            thingsConfigurationInstance = NULL;
+        }
+    }
+
+    std::string ThingsConfiguration::getAttributeByConfigurationName(ConfigurationName name)
+    {
+        for (auto it = ConfigurationUnitTable.begin(); ConfigurationUnitTable.end() != it; it++)
+        {
+            if ((*it).m_name == name)
+                return (*it).m_attribute;
+        }
+
+        return "";
+    }
+
+    std::string ThingsConfiguration::getUriByConfigurationName(ConfigurationName name)
+    {
+        for (auto it = ConfigurationUnitTable.begin(); ConfigurationUnitTable.end() != it; it++)
+        {
+            if ((*it).m_name == name)
+                return (*it).m_uri;
+        }
+
+        return "";
+    }
+
+    std::string ThingsConfiguration::getUpdateVal(std::string conf)
+    {
+        std::map< std::string, ConfigurationRequestEntry >::iterator it =
+                configurationRequestTable.find(conf);
+
+        if (it == configurationRequestTable.end())
+            return NULL;
+        else
+            return it->second.m_updateVal;
+
+    }
+    std::shared_ptr< OCResource > ThingsConfiguration::getResource(std::string conf)
+    {
+        std::map< std::string, ConfigurationRequestEntry >::iterator it =
+                configurationRequestTable.find(conf);
+
+        if (it == configurationRequestTable.end())
+            return NULL;
+        else
+            return it->second.m_resource;
+    }
+
+    ConfigurationCallback ThingsConfiguration::getCallback(std::string conf)
+    {
+        std::map< std::string, ConfigurationRequestEntry >::iterator it =
+                configurationRequestTable.find(conf);
+
+        if (it == configurationRequestTable.end())
+            return NULL;
+        else
+            return it->second.m_callback;
+    }
+
+    std::string ThingsConfiguration::getListOfSupportedConfigurationUnits()
+    {
+        std::string res;
+
+        res = "{\"Configuration Units\":[";
+
+        auto it = ConfigurationUnitTable.begin();
+        while (1)
+        {
+            res = res + (*it).getJSON();
+            it++;
+
+            if (it == ConfigurationUnitTable.end())
+                break;
+            else
+                res += ",";
+        }
+
+        res += "]}";
+
+        return res;
+    }
+
+    std::string ThingsConfiguration::getHostFromURI(std::string oldUri)
+    {
+        size_t f;
+        std::string newUri;
+
+        if ((f = oldUri.find("/factoryset/oic/")) != string::npos)
+            newUri = oldUri.replace(f, oldUri.size(), "");
+        else if ((f = oldUri.find("/oic/")) != string::npos)
+            newUri = oldUri.replace(f, oldUri.size(), "");
+
+        return newUri;
+    }
+
+    void ThingsConfiguration::onDeleteActionSet(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string conf)
+    {
+        std::shared_ptr < OCResource > resource = getResource(conf);
+
+        std::cout << __func__ << std::endl;
+
+        if (resource)
+        {
+            QueryParamsMap query;
+
+            // After deletion of the left action set, find target child resource's URIs by sending
+            // GET message. Note that, this resource is surely a collection resource which has child
+            // resources.
+            resource->get(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsConfiguration::onGetChildInfoForUpdate, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, conf)));
+
+        }
+
+    }
+
+    void ThingsConfiguration::onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string conf)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "GET request was successful" << std::endl;
+
+            std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+            std::vector < OCRepresentation > children = rep.getChildren();
+            for (auto oit = children.begin(); oit != children.end(); ++oit)
+            {
+                std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+            }
+
+            // Get information by using configuration name(conf)
+            std::shared_ptr < OCResource > resource = getResource(conf);
+            std::string actionstring = conf;
+            std::string uri = getUriByConfigurationName(conf);
+            std::string attr = getAttributeByConfigurationName(conf);
+
+            if (uri == "")
+                return;
+
+            if (resource)
+            {
+                // In this nest, we create a new action set of which name is the configuration name.
+                // Required information consists of a host address, URI, attribute key, and
+                // attribute value.
+                ActionSet *newActionSet = new ActionSet();
+                newActionSet->actionsetName = conf;
+
+                for (auto oit = children.begin(); oit != children.end(); ++oit)
+                {
+                    Action *newAction = new Action();
+
+                    // oit->getUri() includes a host address as well as URI.
+                    // We should split these to each other and only use the host address to create
+                    // a child resource's URI. Note that the collection resource and its child
+                    // resource are located in same host.
+                    newAction->target = getHostFromURI(oit->getUri()) + uri;
+
+                    Capability *newCapability = new Capability();
+                    newCapability->capability = attr;
+                    newCapability->status = getUpdateVal(conf);
+
+                    newAction->listOfCapability.push_back(newCapability);
+                    newActionSet->listOfAction.push_back(newAction);
+                }
+
+                // Request to create a new action set by using the above actionSet
+                g_groupmanager->addActionSet(resource, newActionSet,
+                        std::function<
+                                void(const HeaderOptions& headerOptions,
+                                        const OCRepresentation& rep, const int eCode) >(
+                                std::bind(&ThingsConfiguration::onCreateActionSet, this,
+                                        std::placeholders::_1, std::placeholders::_2,
+                                        std::placeholders::_3, conf)));
+
+                free(newActionSet);
+            }
+
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsConfiguration::onGetChildInfoForGet(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string conf)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "GET request was successful" << std::endl;
+            std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+            std::shared_ptr< OCResource > resource, tempResource;
+            std::vector < std::shared_ptr< OCResource > > p_resources;
+            std::vector < std::string > m_if;
+            std::string uri = getUriByConfigurationName(conf);
+
+            if (uri == "")
+                return;
+
+            if (uri == "/oic/con" || uri == "/factoryset" || uri == "/factoryset/oic/con")
+                m_if.push_back(BATCH_INTERFACE);
+            else
+                m_if.push_back(DEFAULT_INTERFACE);
+
+            std::vector < OCRepresentation > children = rep.getChildren();
+            for (auto oit = children.begin(); oit != children.end(); ++oit)
+            {
+                std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+
+                // Using a host address and child URIs, we can dynamically create resource objects.
+                // Note that the child resources have not found before, we have no resource objects.
+                // For this reason, we create the resource objects.
+
+                std::string host = getHostFromURI(oit->getUri());
+                tempResource = OCPlatform::constructResourceObject(host, uri, true,
+                        oit->getResourceTypes(), m_if);
+
+                p_resources.push_back(tempResource);
+            }
+
+            // Send GET messages to the child resources in turn.
+            for (unsigned int i = 0; i < p_resources.size(); ++i)
+            {
+                resource = p_resources.at(i);
+                if (resource)
+                {
+                    try
+                    {
+                        if (isSimpleResource(resource))
+                        {
+                            QueryParamsMap test;
+                            resource->get(test, getCallback(conf));
+                        }
+                        else
+                        {
+                            QueryParamsMap test;
+                            resource->get(resource->getResourceTypes().at(0), BATCH_INTERFACE, test,
+                                    getCallback(conf));
+                        }
+                    }
+                    catch (OCException& e)
+                    {
+                        std::cout << e.reason() << std::endl;
+                    }
+
+                }
+            }
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsConfiguration::onCreateActionSet(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string conf)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "PUT request was successful" << std::endl;
+
+            std::shared_ptr < OCResource > resource = getResource(conf);
+            if (resource)
+            {
+                // Now, it is time to execute the action set.
+                g_groupmanager->executeActionSet(resource, conf,
+                        std::function<
+                                void(const HeaderOptions& headerOptions,
+                                        const OCRepresentation& rep, const int eCode) >(
+                                std::bind(&ThingsConfiguration::onExecuteForGroupAction, this,
+                                        std::placeholders::_1, std::placeholders::_2,
+                                        std::placeholders::_3, conf)));
+            }
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsConfiguration::onExecuteForGroupAction(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string conf)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "PUT request was successful" << std::endl;
+
+            getCallback(conf)(headerOptions, rep, eCode);
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    bool ThingsConfiguration::isSimpleResource(std::shared_ptr< OCResource > resource)
+    {
+
+        for (unsigned int i = 0; i < resource->getResourceTypes().size(); ++i)
+        {
+            if (resource->getResourceTypes().at(i).find(".resourceset", 0) != std::string::npos)
+                return false;
+        }
+
+        return true;
+    }
+
+    bool ThingsConfiguration::hasBatchInterface(std::shared_ptr< OCResource > resource)
+    {
+        for (unsigned int i = 0; i < resource->getResourceInterfaces().size(); ++i)
+        {
+            if (resource->getResourceInterfaces().at(i) == BATCH_INTERFACE)
+                return true;
+        }
+
+        return false;
+    }
+
+    void ThingsConfiguration::onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode, std::string conf)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "Get request was successful" << std::endl;
+
+            getCallback(conf)(headerOptions, rep, eCode);
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsConfiguration::onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode, std::string conf)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "PUT request was successful" << std::endl;
+
+            // Callback
+            getCallback(conf)(headerOptions, rep, eCode);
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    OCStackResult ThingsConfiguration::updateConfigurations(std::shared_ptr< OCResource > resource,
+            std::map< ConfigurationName, ConfigurationValue > configurations,
+            ConfigurationCallback callback)
+    {
+        // For M2, # of configurations is 1
+        // First, mapping a semantic name(ConfigurationUnit) into resource's name(uri ...)
+        if (configurations.size() == 0)
+        {
+            std::cout << "# of request configuration is 0" << std::endl;
+            return OC_STACK_ERROR;
+        }
+
+        if (!resource)
+        {
+            std::cout << "resource is NULL\n";
+            return OC_STACK_ERROR;
+        }
+
+        std::map< ConfigurationName, ConfigurationValue >::iterator it = configurations.begin();
+        std::string conf = it->first; // configuration name
+        std::transform(conf.begin(), conf.end(), conf.begin(), ::tolower); // to lower case
+
+        // Check the request queue if a previous request is still left. If so, remove it.
+        std::map< std::string, ConfigurationRequestEntry >::iterator iter =
+                configurationRequestTable.find(conf);
+        if (iter != configurationRequestTable.end())
+            configurationRequestTable.erase(iter);
+
+        // Create new request entry stored in the queue
+        ConfigurationRequestEntry newCallback(conf, callback, resource, it->second);
+        configurationRequestTable.insert(std::make_pair(conf, newCallback));
+
+        OCRepresentation rep;
+        QueryParamsMap query;
+        if (isSimpleResource(resource))
+        {
+            // This resource does not need to use a group manager. Just send a PUT message
+            rep.setValue(getAttributeByConfigurationName(conf), getUpdateVal(conf));
+            return resource->put(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, rep, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsConfiguration::onGet, this, std::placeholders::_1,
+                                    std::placeholders::_2, std::placeholders::_3, conf)));
+        }
+        else
+        {
+            // This resource is a collection resource which uses group manager functionalities.
+            // First, delete an existing action set of which name is same as a current action set
+            // name. As of now, the name is determined by "Configuration Name" which a user just
+            // specifies.
+            return g_groupmanager->deleteActionSet(resource, conf,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsConfiguration::onDeleteActionSet, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, conf)));
+        }
+    }
+
+    OCStackResult ThingsConfiguration::getConfigurations(std::shared_ptr< OCResource > resource,
+            std::vector< ConfigurationName > configurations, ConfigurationCallback callback)
+    {
+        // For M2, # of configurations is 1
+        // First, mapping a semantic name(ConfigurationUnit) into resource's name(uri ...)
+        if (configurations.size() == 0)
+        {
+            std::cout << "# of request configuration is 0" << std::endl;
+            return OC_STACK_ERROR;
+        }
+        if (!resource)
+        {
+            std::cout << "resource is NULL\n";
+            return OC_STACK_ERROR;
+        }
+
+        std::vector< ConfigurationName >::iterator it = configurations.begin();
+        std::string conf = (*it); // configuration name
+        std::transform(conf.begin(), conf.end(), conf.begin(), ::tolower); // to lower case
+
+        // Check the request queue if a previous request is still left. If so, remove it.
+        std::map< std::string, ConfigurationRequestEntry >::iterator iter =
+                configurationRequestTable.find(conf);
+        if (iter != configurationRequestTable.end())
+            configurationRequestTable.erase(iter);
+
+        // Create new request entry stored in the queue
+        ConfigurationRequestEntry newCallback(conf, callback, resource, conf);
+        configurationRequestTable.insert(std::make_pair(conf, newCallback));
+
+        QueryParamsMap query;
+        OCRepresentation rep;
+
+        if (isSimpleResource(resource))
+        {
+            // This resource is a simple resource. Just send a PUT message
+            std::string m_if = DEFAULT_INTERFACE;
+
+            if (hasBatchInterface(resource))
+                m_if = BATCH_INTERFACE;
+
+            return resource->get(resource->getResourceTypes().at(0), m_if, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsConfiguration::onGet, this, std::placeholders::_1,
+                                    std::placeholders::_2, std::placeholders::_3, conf)));
+        }
+        else
+        {
+            // This resource is a collection resource. On the contrary of a update, it does not use
+            // group manager functionality. It just acquires child resource's URI and send GET
+            // massages to the child resources in turn.
+            // First, request the child resources's URI.
+            return resource->get(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsConfiguration::onGetChildInfoForGet, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, conf)));
+        }
+
+    }
+
+// callback handler on GET request
+    void ThingsConfiguration::onGetBootstrapInformation(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            g_bootstrapCallback(headerOptions, rep, eCode);
+        }
+
+        else
+        {
+            std::cout << "onGET Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsConfiguration::onFoundBootstrapServer(
+            std::vector< std::shared_ptr< OCResource > > resources)
+    {
+        std::string resourceURI;
+        std::string hostAddress;
+
+        try
+        {
+            // Do some operations with resource object.
+            for (unsigned int i = 0; i < resources.size(); ++i)
+            {
+                std::shared_ptr < OCResource > resource = resources.at(i);
+
+                if (resource)
+                { // Request configuration resources
+
+                    std::cout << "Getting bootstrap server representation on: " << DEFAULT_INTERFACE
+                            << std::endl;
+
+                    resource->get("bootstrap", DEFAULT_INTERFACE, QueryParamsMap(),
+                            &onGetBootstrapInformation);
+
+                }
+                else
+                {
+                    // Resource is invalid
+                    std::cout << "Resource is invalid" << std::endl;
+                }
+            }
+
+        }
+        catch (std::exception& e)
+        {
+            //log(e.what());
+        }
+    }
+
+    OCStackResult ThingsConfiguration::doBootstrap(ConfigurationCallback callback)
+    {
+        g_bootstrapCallback = callback;
+
+        // Find bootstrap server.
+        std::vector < std::string > type;
+        type.push_back("bootstrap");
+
+        std::cout << "Finding Bootstrap Server resource... " << std::endl;
+        return g_groupmanager->findCandidateResources(type, &onFoundBootstrapServer);
+    }
+}
diff --git a/service/things-manager/sdk/src/ThingsConfiguration.h b/service/things-manager/sdk/src/ThingsConfiguration.h
new file mode 100644 (file)
index 0000000..79e2579
--- /dev/null
@@ -0,0 +1,546 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file   ThingsConfiguration.h
+
+/// @brief  This file contains the declaration of classes and its members related to
+///         ThingsConfiguration.
+
+#ifndef __OC_THINGSCONFIGURATION__
+#define __OC_THINGSCONFIGURATION__
+
+#include <string>
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include "GroupManager.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+
+namespace OIC
+{
+/// Declearation of Configuation Callback funtion type
+    typedef std::function<
+            void(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+            > ConfigurationCallback;
+
+    typedef std::string ConfigurationName;
+    typedef std::string ConfigurationValue;
+
+    /**
+     * @brief
+     * The following class is used as a item stacking in request queue. The class stores a request
+     * and referential information (e.g., a configuration name, a target resource object, a callback
+     * function passed from the applications, and a update value). When the function for updating/
+     * getting configuration value is called from applications, this class instance is created and
+     * stored in the request queue. The queue is maintained in a std::map structure so if desiring
+     * to find a specific request, you can find it by querying a configuration name.
+     */
+    class ConfigurationRequestEntry
+    {
+    public:
+        ConfigurationRequestEntry(std::string ID, ConfigurationCallback callback,
+                std::shared_ptr< OCResource > resource, std::string updateVal):
+                m_ID(ID), m_callback(callback), m_resource(resource), m_updateVal(updateVal)
+        {
+        }
+        ;
+
+        // Configuration Name (used in key value in std::map structure)
+        // e.g., time, network, security, and so on
+        std::string m_ID;
+        // Reference callback pointer
+        ConfigurationCallback m_callback;
+        // Reference resource object
+        std::shared_ptr< OCResource > m_resource;
+        // Update value only used for configuration update
+        std::string m_updateVal;
+    };
+
+    /**
+     * @brief
+     * The following class is used to store providing configuration name and its relevant
+     * information. The relevant information includes a brief description, uri, and attribute key.
+     * Note that a developer only specifies a configuration name, not URI nor attribute key, to
+     * update/get a value to a remote. Thus, using configuration name, we convert it to more
+     * specific information (i.e. uri and attribute key) to send a request. This class is reponsible
+     * to storing these information.
+     */
+    class ConfigurationUnitInfo
+    {
+    public:
+
+        std::string m_name;
+        std::string m_description;
+        std::string m_uri;
+        std::string m_attribute;
+
+        ConfigurationUnitInfo(std::string name, std::string description, std::string uri,
+                std::string attribute) :
+                m_name(name), m_description(description), m_uri(uri), m_attribute(attribute)
+        {
+        }
+        ;
+
+        // If a developer wants to know a list of configuration names, gives it in JSON format.
+        std::string getJSON()
+        {
+            std::string res;
+
+            res = "{\"name\":\"" + m_name + "\",\"description\":\"" + m_description + "\"}";
+
+            return res;
+        }
+    };
+
+#define NUMCONFUNIT 6
+    typedef std::string ConfigurationName;
+    typedef std::string ConfigurationValue;
+
+    class ThingsConfiguration
+    {
+    public:
+        /**
+         * Constructor for ThingsConfiguration. Constructs a new ThingsConfiguration
+         */
+        ThingsConfiguration(void)
+        {
+            ConfigurationUnitInfo unit[] =
+            {
+            { "configuration", "Configuration Collection's value and its child resource's value",
+                    "/oic/con", "value" },
+            { "region", "the current region in which the device is located geographically",
+                    "/oic/con/0/region", "value" },
+            { "timelink", "link of time collection.", "/oic/con/0/time", "link" },
+            { "ipaddress", "IP Address", "/oic/con/network/0/IPAddress", "value" },
+            { "securitymode",
+                    "Resource for security information (credentials, access control list etc.)",
+                    "/oic/con/security/0/mode", "value" },
+                    { "getfactoryset", "get all default configuration value", "/factoryset/oic/con",
+                            "value" } };
+
+            for (int i = 0; i < NUMCONFUNIT; i++)
+                ConfigurationUnitTable.push_back(unit[i]);
+        }
+        ;
+
+        /**
+         * Virtual destructor
+         */
+        ~ThingsConfiguration(void)
+        {
+        }
+        ;
+
+        static ThingsConfiguration *thingsConfigurationInstance;
+        static ThingsConfiguration* getInstance();
+        void deleteInstance();
+
+        void setGroupManager(GroupManager *groupmanager)
+        {
+            g_groupmanager = groupmanager;
+        }
+        ;
+
+        /**
+         * API for updating configuration value of multiple things of a target group or a single
+         * thing.
+         * Callback is called when a response arrives.
+         * Before using the below function, a developer should acquire a resource pointer of
+         * (collection) resource that he want to send a request by calling findResource() function
+         * provided in OCPlatform. And he should also notice a "Configuration Name" term which
+         * represents a nickname of a target attribute of a resource that he wants to update.
+         * The base motivation to introduce the term is to avoid a usage of URI to access a resource
+         * from a developer. Thus, a developer should know which configuration names are supported
+         * by Things Configuration class and what the configuration name means.
+         * To get a list of supported configuration names, use getListOfSupportedConfigurationUnits(
+         * ) function, which provides the list in JSON format.
+         * NOTICE: A series of callback functions is called from updateConfigurations() function:
+         * (1) For a collection resource
+         * updateConfiguration()->onDeleteActionSet()->onGetChildInfoForUpdate()->onCreateActionSet(
+         * )->...(CoAP msg. is transmitted)->OnExecuteForGroupAction()->callback function in APP.
+         * (2) For a simple resource
+         * updateConfiguration()->...(CoAP msg. is transmitted)->OnPut()->callback function in APP.
+         *
+         * @param resource - resource pointer representing the target group or the single thing.
+         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
+         *                         (e.g., installedlocation, currency, (IP)address)
+         *                         Value : a value to be updated
+         * @param callback - callback.
+         *
+         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult updateConfigurations(std::shared_ptr< OCResource > resource,
+                std::map< ConfigurationName, ConfigurationValue > configurations,
+                ConfigurationCallback callback);
+
+        /**
+         * API for getting configuration value of multiple things of a target group or a single
+         * thing.
+         * Callback is called when a response arrives.
+         * NOTICE: A series of callback functions is called from getConfigurations() function:
+         * (1) For a collection resource
+         * getConfigurations()->onGetChildInfoForGet()->...(CoAP msg. is transmitted)
+         * ->callback function in APP.
+         * (2) For a simple resource
+         * getConfigurations()->...(CoAP msg. is transmitted)->onGet()->callback function in APP.
+         *
+         * @param resource - resource pointer representing the target group or the single thing.
+         * @param configurations - ConfigurationUnit: a nickname of attribute of target resource.
+         * @param callback - callback.
+         *
+         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult getConfigurations(std::shared_ptr< OCResource > resource,
+                std::vector< ConfigurationName > configurations, ConfigurationCallback callback);
+
+        /**
+         * API to show a list of supported configuration units (configurable parameters)
+         * Callback call when a response arrives.
+         *
+         * @return the list in JSON format
+         */
+        std::string getListOfSupportedConfigurationUnits();
+
+        /**
+         * API for bootstrapping functionality. Find a bootstrap server and get configuration
+         * information from the bootstrap server. With the information, make a configuration
+         * resource.
+         *
+         * @param callback - callback.
+         *
+         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult doBootstrap(ConfigurationCallback callback);
+
+    private:
+
+        GroupManager *g_groupmanager;
+
+        std::vector< ConfigurationUnitInfo > ConfigurationUnitTable;
+
+        void onExecuteForGroupAction(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+        void onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+        void onGetChildInfoForGet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                const int eCode, std::string conf);
+        void onCreateActionSet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                const int eCode, std::string conf);
+        void onGetActionSet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                const int eCode, std::string conf);
+        void onDeleteActionSet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                const int eCode, std::string conf);
+        void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode,
+                std::string conf);
+        void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode,
+                std::string conf);
+        static void onFoundBootstrapServer(std::vector< std::shared_ptr< OCResource > > resources);
+        static void onGetBootstrapInformation(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode);
+        // Copyright 2014 Samsung Electronics All Rights Reserved.
+
+        /// @file   ThingsConfiguration.h
+
+        /// @brief  This file contains the declaration of classes and its members related to
+        ///         ThingsConfiguration.
+
+#ifndef __OC_THINGSCONFIGURATION__
+#define __OC_THINGSCONFIGURATION__
+
+#include <string>
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include "GroupManager.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+        using namespace OC;
+
+/// Declearation of Configuation Callback funtion type
+        typedef std::function<
+        void(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode) > ConfigurationCallback;
+
+        typedef std::string ConfigurationName;
+        typedef std::string ConfigurationValue;
+
+        /**
+         * @brief
+         * The following class is used as a item stacking in request queue. The class stores a
+         * request and referential information (e.g., a configuration name, a target resource
+         * object, a callback function passed from the applications, and a update value). When the
+         * function for updating/getting configuration value is called from applications, this class
+         * instance is created and stored in the request queue. The queue is maintained in
+         * a std::map structure so if desiring to find a specific request, you can find it
+         * by querying a configuration name.
+         */
+        class ConfigurationRequestEntry
+        {
+        public:
+            ConfigurationRequestEntry(std::string ID, ConfigurationCallback callback,
+                    std::shared_ptr< OCResource > resource, std::string updateVal) :
+            m_ID(ID), m_callback(callback), m_resource(resource), m_updateVal(updateVal)
+            {
+            }
+            ;
+
+            // Configuration Name (used in key value in std::map structure)
+            // e.g., time, network, security, and so on
+            std::string m_ID;
+            // Reference callback pointer
+            ConfigurationCallback m_callback;
+            // Reference resource object
+            std::shared_ptr< OCResource > m_resource;
+            // Update value only used for configuration update
+            std::string m_updateVal;
+        };
+
+        /**
+         * @brief
+         * The following class is used to store providing configuration name and its relevant
+         * information. The relevant information includes a brief description, uri, and attribute
+         * key. Note that a developer only specifies a configuration name, not URI nor attribute
+         * key, to update/get a value to a remote. Thus, using configuration name, we convert it to
+         * more specific information (i.e. uri and attribute key) to send a request. This class is
+         * reponsible to storing these information.
+         */
+        class ConfigurationUnitInfo
+        {
+        public:
+
+            std::string m_name;
+            std::string m_description;
+            std::string m_uri;
+            std::string m_attribute;
+
+            ConfigurationUnitInfo(std::string name, std::string description, std::string uri,
+                    std::string attribute) :
+            m_name(name), m_description(description), m_uri(uri), m_attribute(attribute)
+            {
+            }
+            ;
+
+            // If a developer wants to know a list of configuration names, gives it in JSON format.
+            std::string getJSON()
+            {
+                std::string res;
+
+                res = "{\"name\":\"" + m_name + "\",\"description\":\"" + m_description + "\"}";
+
+                return res;
+            }
+        };
+
+#define NUMCONFUNIT 6
+        typedef std::string ConfigurationName;
+        typedef std::string ConfigurationValue;
+
+        class ThingsConfiguration
+        {
+        public:
+            /**
+             * Constructor for ThingsConfiguration. Constructs a new ThingsConfiguration
+             */
+            ThingsConfiguration(void)
+            {
+                ConfigurationUnitInfo unit[] =
+                {
+                    {   "configuration", "Configuration value and its child resource's value",
+                            "/oic/con", "value"},
+                    {   "region", "the current region in which the Thing is located geographically",
+                        "/oic/con/0/region", "value"},
+                    {   "timelink", "link of time collection.", "/oic/con/0/time", "link"},
+                    {   "ipaddress", "IP Address", "/oic/con/network/0/IPAddress", "value"},
+                    {   "securitymode",
+                        "Resource for security information (credentials, access control list etc.)",
+                        "/oic/con/security/0/mode", "value"},
+                    {   "getfactoryset", "get all default configuration value",
+                        "/factoryset/oic/con", "value"}};
+
+                for (int i = 0; i < NUMCONFUNIT; i++)
+                ConfigurationUnitTable.push_back(unit[i]);
+            }
+            ;
+
+            /**
+             * Virtual destructor
+             */
+            ~ThingsConfiguration(void)
+            {
+            }
+            ;
+
+            static ThingsConfiguration *thingsConfigurationInstance;
+            static ThingsConfiguration* getInstance();
+            void deleteInstance();
+
+            void setGroupManager(GroupManager *groupmanager)
+            {
+                g_groupmanager = groupmanager;
+            }
+            ;
+
+            /**
+             * API for updating configuration value of multiple things of a target group or a single
+             * thing.
+             * Callback is called when a response arrives.
+             * Before using the below function, a developer should acquire a resource pointer of
+             * (collection) resource that he want to send a request by calling findResource()
+             * function provided in OCPlatform. And he should also notice a "Configuration Name"
+             * term which represents a nickname of a target attribute of a resource that he wants to
+             * update.
+             * The base motivation to introduce the term is to avoid a usage of URI to access
+             * a resource from a developer. Thus, a developer should know which configuration names
+             * are supported by Things Configuration class and what the configuration name means.
+             * To get a list of supported configuration names, use getListOfSupportedConfigurationU-
+             * nits() function, which provides the list in JSON format.
+             * NOTICE: A series of callback functions is called from updateConfigurations() function
+             * (1) For a collection resource
+             * updateConfiguration()->onDeleteActionSet()->onGetChildInfoForUpdate()->onCreateActio-
+             * nSet()->...(CoAP msg. is transmitted)->OnExecuteForGroupAction()->callback function
+             * in APP.
+             * (2) For a simple resource
+             * updateConfiguration()->...(CoAP msg. is transmitted)->OnPut()->callback function in
+             * APP.
+             *
+             * @param resource - resource pointer representing the target group or the single thing.
+             * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
+             *                         (e.g., installedlocation, currency, (IP)address)
+             *                         Value : a value to be updated
+             * @param callback - callback.
+             *
+             * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+             *
+             * NOTE: OCStackResult is defined in ocstack.h.
+             */
+            OCStackResult updateConfigurations(std::shared_ptr< OCResource > resource,
+                    std::map< ConfigurationName, ConfigurationValue > configurations,
+                    ConfigurationCallback callback);
+
+            /**
+             * API for getting configuration value of multiple things of a target group or a single
+             * thing.
+             * Callback is called when a response arrives.
+             * NOTICE: A series of callback functions is called from getConfigurations() function:
+             * (1) For a collection resource
+             * getConfigurations()->onGetChildInfoForGet()->...(CoAP msg. is transmitted)
+             * ->callback function in APP.
+             * (2) For a simple resource
+             * getConfigurations()->...(CoAP msg. is transmitted)->onGet()->callback function in APP
+             *
+             * @param resource - resource pointer representing the target group or the single thing.
+             * @param configurations - ConfigurationUnit: a nickname of attribute of target resource
+             * @param callback - callback.
+             *
+             * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+             *
+             * NOTE: OCStackResult is defined in ocstack.h.
+             */
+            OCStackResult getConfigurations(std::shared_ptr< OCResource > resource,
+                    std::vector< ConfigurationName > configurations, ConfigurationCallback callback);
+
+            /**
+             * API to show a list of supported configuration units (configurable parameters)
+             * Callback call when a response arrives.
+             *
+             * @return the list in JSON format
+             */
+            std::string getListOfSupportedConfigurationUnits();
+
+            /**
+             * API for bootstrapping functionality. Find a bootstrap server and get configuration
+             * information from the bootstrap server. With the information, make a configuration
+             * resource.
+             *
+             * @param callback - callback.
+             *
+             * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+             *
+             * NOTE: OCStackResult is defined in ocstack.h.
+             */
+            OCStackResult doBootstrap(ConfigurationCallback callback);
+
+        private:
+
+            GroupManager *g_groupmanager;
+
+            std::vector< ConfigurationUnitInfo > ConfigurationUnitTable;
+
+            void onExecuteForGroupAction(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onGetChildInfoForGet(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onCreateActionSet(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onGetActionSet(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onDeleteActionSet(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onGet(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            void onPut(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+            static void onFoundBootstrapServer(std::vector< std::shared_ptr< OCResource >
+                > resources);
+            static void onGetBootstrapInformation(const HeaderOptions& headerOptions,
+                    const OCRepresentation& rep, const int eCode);
+
+            std::shared_ptr< OCResource > getResource(std::string conf);
+            ConfigurationCallback getCallback(std::string conf);
+            std::string getUpdateVal(std::string conf);
+            std::string getAttributeByConfigurationName(ConfigurationName name);
+            std::string getUriByConfigurationName(ConfigurationName name);
+
+            std::string getHostFromURI(std::string oldUri);
+
+            bool isSimpleResource(std::shared_ptr< OCResource > resource);
+            bool hasBatchInterface(std::shared_ptr< OCResource > resource);
+
+        };
+
+#endif  /* __OC_THINGSCONFIGURATION__*/
+
+        std::shared_ptr< OCResource > getResource(std::string conf);
+        ConfigurationCallback getCallback(std::string conf);
+        std::string getUpdateVal(std::string conf);
+        std::string getAttributeByConfigurationName(ConfigurationName name);
+        std::string getUriByConfigurationName(ConfigurationName name);
+
+        std::string getHostFromURI(std::string oldUri);
+
+        bool isSimpleResource(std::shared_ptr< OCResource > resource);
+        bool hasBatchInterface(std::shared_ptr< OCResource > resource);
+
+    };
+}
+#endif  /* __OC_THINGSCONFIGURATION__*/
+
diff --git a/service/things-manager/sdk/src/ThingsDiagnostics.cpp b/service/things-manager/sdk/src/ThingsDiagnostics.cpp
new file mode 100644 (file)
index 0000000..7eccc62
--- /dev/null
@@ -0,0 +1,395 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file    ThingsDiagnostics.cpp
+///  @brief
+
+#include <OCApi.h>
+#include <OCPlatform.h>
+#include <cstdlib>
+
+#include "ThingsDiagnostics.h"
+
+using namespace OC;
+
+namespace OIC
+{
+    const int SUCCESS_RESPONSE = 0;
+
+    std::map< std::string, DiagnosticsRequestEntry > diagnosticsRequestTable;
+
+    ThingsDiagnostics* ThingsDiagnostics::thingsDiagnosticsInstance = NULL;
+
+    ThingsDiagnostics* ThingsDiagnostics::getInstance()
+    {
+        if (thingsDiagnosticsInstance == NULL)
+        {
+            thingsDiagnosticsInstance = new ThingsDiagnostics();
+        }
+        return thingsDiagnosticsInstance;
+    }
+
+    void ThingsDiagnostics::deleteInstance()
+    {
+        if (thingsDiagnosticsInstance)
+        {
+            delete thingsDiagnosticsInstance;
+            thingsDiagnosticsInstance = NULL;
+        }
+    }
+
+    std::string ThingsDiagnostics::getAttributeByDiagnosticsName(DiagnosticsName name)
+    {
+        for (auto it = DiagnosticsUnitTable.begin(); DiagnosticsUnitTable.end() != it; it++)
+        {
+            if ((*it).m_name == name)
+                return (*it).m_attribute;
+        }
+
+        return "";
+    }
+
+    std::string ThingsDiagnostics::getUriByDiagnosticsName(DiagnosticsName name)
+    {
+        for (auto it = DiagnosticsUnitTable.begin(); DiagnosticsUnitTable.end() != it; it++)
+        {
+            if ((*it).m_name == name)
+                return (*it).m_uri;
+        }
+
+        return "";
+    }
+
+    std::string ThingsDiagnostics::getUpdateVal(std::string diag)
+    {
+        std::map< std::string, DiagnosticsRequestEntry >::iterator it =
+                diagnosticsRequestTable.find(diag);
+
+        if (it == diagnosticsRequestTable.end())
+            return NULL;
+        else
+            return it->second.m_updateVal;
+
+    }
+    std::shared_ptr< OCResource > ThingsDiagnostics::getResource(std::string diag)
+    {
+        std::map< std::string, DiagnosticsRequestEntry >::iterator it =
+                diagnosticsRequestTable.find(diag);
+
+        if (it == diagnosticsRequestTable.end())
+            return NULL;
+        else
+            return it->second.m_resource;
+    }
+
+    DiagnosticsCallback ThingsDiagnostics::getCallback(std::string diag)
+    {
+        std::map< std::string, DiagnosticsRequestEntry >::iterator it =
+                diagnosticsRequestTable.find(diag);
+
+        if (it == diagnosticsRequestTable.end())
+            return NULL;
+        else
+            return it->second.m_callback;
+    }
+
+    std::string ThingsDiagnostics::getHostFromURI(std::string oldUri)
+    {
+        size_t f;
+        std::string newUri;
+
+        if ((f = oldUri.find("/factoryset/oic/")) != string::npos)
+            newUri = oldUri.replace(f, oldUri.size(), "");
+        else if ((f = oldUri.find("/oic/")) != string::npos)
+            newUri = oldUri.replace(f, oldUri.size(), "");
+
+        return newUri;
+    }
+
+    std::string ThingsDiagnostics::getListOfSupportedDiagnosticsUnits()
+    {
+        std::string res;
+
+        res = "{\"Diagnostics Units\":[";
+
+        auto it = DiagnosticsUnitTable.begin();
+        while (1)
+        {
+            res = res + (*it).getJSON();
+            it++;
+
+            if (it == DiagnosticsUnitTable.end())
+                break;
+            else
+                res += ",";
+        }
+
+        res += "]}";
+
+        return res;
+    }
+
+    void ThingsDiagnostics::onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string diag)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "GET request was successful" << std::endl;
+
+            std::cout << "\tResource URI: " << rep.getUri() << std::endl;
+
+            std::vector < OCRepresentation > children = rep.getChildren();
+            for (auto oit = children.begin(); oit != children.end(); ++oit)
+            {
+                std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl;
+            }
+
+            // Get information by using diagnostics name(diag)
+            std::shared_ptr < OCResource > resource = getResource(diag);
+            std::string actionstring = diag;
+            std::string uri = getUriByDiagnosticsName(diag);
+            std::string attr = getAttributeByDiagnosticsName(diag);
+
+            if (uri == "")
+                return;
+
+            if (resource)
+            {
+                // In this nest, we create a new action set of which name is the dignostics name.
+                // Required information consists of a host address, URI, attribute key, and
+                // attribute value.
+                ActionSet *newActionSet = new ActionSet();
+                newActionSet->actionsetName = diag;
+
+                for (auto oit = children.begin(); oit != children.end(); ++oit)
+                {
+                    Action *newAction = new Action();
+
+                    // oit->getUri() includes a host address as well as URI.
+                    // We should split these to each other and only use the host address to create
+                    // a child resource's URI. Note that the collection resource and its child
+                    // resource are located in same host.
+                    newAction->target = getHostFromURI(oit->getUri()) + uri;
+
+                    Capability *newCapability = new Capability();
+                    newCapability->capability = attr;
+                    newCapability->status = getUpdateVal(diag);
+
+                    newAction->listOfCapability.push_back(newCapability);
+                    newActionSet->listOfAction.push_back(newAction);
+                }
+
+                // Request to create a new action set by using the above actionSet
+                g_groupmanager->addActionSet(resource, newActionSet,
+                        std::function<
+                                void(const HeaderOptions& headerOptions,
+                                        const OCRepresentation& rep, const int eCode) >(
+                                std::bind(&ThingsDiagnostics::onCreateActionSet, this,
+                                        std::placeholders::_1, std::placeholders::_2,
+                                        std::placeholders::_3, diag)));
+
+                free(newActionSet);
+
+            }
+
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsDiagnostics::onCreateActionSet(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string diag)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "PUT request was successful" << std::endl;
+
+            std::shared_ptr < OCResource > resource = getResource(diag);
+            if (resource)
+            {
+                // Now, it is time to execute the action set.
+                g_groupmanager->executeActionSet(resource, diag,
+                        std::function<
+                                void(const HeaderOptions& headerOptions,
+                                        const OCRepresentation& rep, const int eCode) >(
+                                std::bind(&ThingsDiagnostics::onExecuteForGroupAction, this,
+                                        std::placeholders::_1, std::placeholders::_2,
+                                        std::placeholders::_3, diag)));
+            }
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsDiagnostics::onExecuteForGroupAction(const HeaderOptions& headerOptions,
+            const OCRepresentation& rep, const int eCode, std::string diag)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "PUT request was successful" << std::endl;
+
+            getCallback(diag)(headerOptions, rep, eCode);
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    void ThingsDiagnostics::onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+            const int eCode, std::string diag)
+    {
+        if (eCode == SUCCESS_RESPONSE)
+        {
+            std::cout << "PUT request was successful" << std::endl;
+
+            getCallback(diag)(headerOptions, rep, eCode);
+        }
+        else
+        {
+            std::cout << "onPut Response error: " << eCode << std::endl;
+            std::exit(-1);
+        }
+    }
+
+    bool ThingsDiagnostics::isSimpleResource(std::shared_ptr< OCResource > resource)
+    {
+        for (unsigned int i = 0; i < resource->getResourceTypes().size(); ++i)
+        {
+            if (resource->getResourceTypes().at(0).find(".resourceset", 0) != std::string::npos)
+                return false;
+        }
+
+        return true;
+    }
+
+    OCStackResult ThingsDiagnostics::reboot(std::shared_ptr< OCResource > resource,
+            DiagnosticsCallback callback)
+    {
+        if (!resource)
+        {
+            std::cout << "resource is NULL\n";
+            return OC_STACK_ERROR;
+        }
+
+        std::string diag = "reboot";
+
+        // Check the request queue if a previous request is still left. If so, remove it.
+        std::map< std::string, DiagnosticsRequestEntry >::iterator iter =
+                diagnosticsRequestTable.find(diag);
+        if (iter != diagnosticsRequestTable.end())
+            diagnosticsRequestTable.erase(iter);
+
+        // Create new request entry stored in the queue
+        DiagnosticsRequestEntry newCallback(diag, callback, resource, "true");
+        diagnosticsRequestTable.insert(std::make_pair(diag, newCallback));
+
+        QueryParamsMap query;
+        OCRepresentation rep;
+
+        if (isSimpleResource(resource))
+        {
+            // This resource is a simple resource. Just send a PUT message
+            OCRepresentation rep;
+            rep.setValue < std::string > (diag, "true");
+
+            return resource->put(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, rep, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onPut, this, std::placeholders::_1,
+                                    std::placeholders::_2, std::placeholders::_3, diag)));
+        }
+        else
+        {
+            // This resource is a collection resource. It just acquires child resource's URI and
+            // send GET massages to the child resources in turn.
+            // First, request the child resources's URI.
+            // TODO: Add a deletion of actionset
+            return resource->get(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onGetChildInfoForUpdate, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, diag)));
+        }
+    }
+
+    OCStackResult ThingsDiagnostics::factoryReset(std::shared_ptr< OCResource > resource,
+            DiagnosticsCallback callback)
+    {
+        if (!resource)
+        {
+            std::cout << "resource is NULL\n";
+            return OC_STACK_ERROR;
+        }
+
+        std::string diag = "factoryreset";
+
+        // Check the request queue if a previous request is still left. If so, remove it.
+        std::map< std::string, DiagnosticsRequestEntry >::iterator iter =
+                diagnosticsRequestTable.find(diag);
+        if (iter != diagnosticsRequestTable.end())
+            diagnosticsRequestTable.erase(iter);
+
+        // Create new request entry stored in the queue
+        DiagnosticsRequestEntry newCallback(diag, callback, resource, "true");
+        diagnosticsRequestTable.insert(std::make_pair(diag, newCallback));
+
+        QueryParamsMap query;
+        OCRepresentation rep;
+
+        if (isSimpleResource(resource))
+        {
+            // This resource is a simple resource. Just send a PUT message
+            OCRepresentation rep;
+            rep.setValue < std::string > ("value", "true");
+
+            return resource->put(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, rep, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onPut, this, std::placeholders::_1,
+                                    std::placeholders::_2, std::placeholders::_3, diag)));
+        }
+        else
+        {
+            // This resource is a collection resource. It just acquires child resource's URI and
+            // send GET massages to the child resources in turn.
+            // First, request the child resources's URI.
+            // TODO: Add a deletion of actionset
+            return resource->get(resource->getResourceTypes().at(0), DEFAULT_INTERFACE, query,
+                    std::function<
+                            void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                                    const int eCode) >(
+                            std::bind(&ThingsDiagnostics::onGetChildInfoForUpdate, this,
+                                    std::placeholders::_1, std::placeholders::_2,
+                                    std::placeholders::_3, diag)));
+        }
+    }
+}
diff --git a/service/things-manager/sdk/src/ThingsDiagnostics.h b/service/things-manager/sdk/src/ThingsDiagnostics.h
new file mode 100644 (file)
index 0000000..dda9362
--- /dev/null
@@ -0,0 +1,223 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file   ThingsDiagnostics.h
+
+/// @brief  This file contains the declaration of classes and its members related to
+///         ThingsDiagnostics.
+
+#ifndef __OC_THINGSDIAGNOSTICS__
+#define __OC_THINGSDIAGNOSTICS__
+
+#include <string>
+#include <vector>
+#include <map>
+#include <cstdlib>
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "GroupManager.h"
+
+using namespace OC;
+namespace OIC
+{
+
+    /// Declearation of Diagnostics Callback funtion type
+    typedef std::function<
+            void(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode)
+            > DiagnosticsCallback;
+
+    /**
+     *  @brief
+     *  The following class is used as a item stacking in request queue. The class stores a request
+     *  and referential information (e.g., a diagnostics name, a target resource object, a callback
+     *  function passed from the applications, and a update value). When the function for updating/
+     *  getting diagnostics value is called from applications, this class instance is created and
+     *  stored in the request queue. The queue is maintained in a std::map structure so if desiring
+     *  to find a specific request, you can find it by querying a diagnostics name.
+     */
+    class DiagnosticsRequestEntry
+    {
+    public:
+        DiagnosticsRequestEntry(std::string ID, DiagnosticsCallback callback,
+                std::shared_ptr< OCResource > resource, std::string updateVal) :
+                m_ID(ID), m_callback(callback), m_resource(resource), m_updateVal(updateVal)
+        {
+        }
+        ;
+
+        // Diagnostics Name (used in key value in std::map structure)
+        // e.g., reboot and factoryset
+        std::string m_ID;
+
+        // Reference callback pointer
+        DiagnosticsCallback m_callback;
+
+        // Reference resource object
+        std::shared_ptr< OCResource > m_resource;
+
+        // Update value only used for diagnostics update (always "true")
+        std::string m_updateVal;
+    };
+
+    /**
+     *  @brief
+     *  The following class is used to store providing diagnostics name and its relevant information
+     *  The relevant information includes a brief description, uri, and attribute key.
+     *  Note that a developer only specifies a diagnostics name, not URI nor attribute key, to
+     *  update a value to a remote. Thus, using diagnostics name, we convert it to more specific
+     *  information (i.e. uri and attribute key) to send a request. This class is reponsible to
+     *  storing these information.
+     */
+    class DiagnosticsUnitInfo
+    {
+    public:
+        DiagnosticsUnitInfo(std::string name, std::string description, std::string uri,
+                std::string attribute) :
+                m_name(name), m_description(description), m_uri(uri), m_attribute(attribute)
+        {
+        }
+        ;
+
+        std::string m_name;
+        std::string m_description;
+        std::string m_uri;
+        std::string m_attribute;
+
+        // If a developer wants to know a list of diagnostics names, gives it in JSON format.
+        std::string getJSON()
+        {
+            std::string res;
+
+            res = "{\"name\":\"" + m_name + "\",\"description\":\"" + m_description + "\"}";
+
+            return res;
+        }
+    };
+
+#define NUMDIAGUNIT 3
+    typedef std::string DiagnosticsName;
+    typedef std::string DiagnosticsValue;
+
+    class ThingsDiagnostics
+    {
+    public:
+        /**
+         * Constructor for ThingsDiagnostics. Constructs a new ThingsDiagnostics
+         */
+        ThingsDiagnostics(void)
+        {
+            DiagnosticsUnitInfo unit[] =
+                    {
+                    { "reboot", "reboot", "/oic/diag/0/reboot", "value" },
+                            { "value",
+                                    "Collecting any device statistics",
+                                    "/oic/diag/0/startCollection", "value" },
+                            { "factoryreset", "restore all configuration values to default values",
+                                    "/oic/diag/0/factoryReset", "value" } };
+
+            for (int i = 0; i < NUMDIAGUNIT; i++)
+                DiagnosticsUnitTable.push_back(unit[i]);
+        }
+        ;
+
+        /**
+         * Virtual destructor
+         */
+        ~ThingsDiagnostics(void)
+        {
+        }
+        ;
+
+        static ThingsDiagnostics *thingsDiagnosticsInstance;
+        static ThingsDiagnostics* getInstance();
+        void deleteInstance();
+
+        void setGroupManager(GroupManager *groupmanager)
+        {
+            g_groupmanager = groupmanager;
+        }
+        ;
+
+        /**
+         * API to make things reboot
+         * Callback call when a response arrives.
+         *
+         * @param resource - resource pointer representing the target group
+         * @param callback - callback.
+         *
+         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+        OCStackResult reboot(std::shared_ptr< OCResource > resource, DiagnosticsCallback callback);
+
+        /**
+         * API for factory reset on device
+         * Callback call when a response arrives.
+         *
+         * @param resource - resource pointer representing the target group
+         * @param callback - callback.
+         *
+         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+         *
+         * NOTE: OCStackResult is defined in ocstack.h.
+         */
+
+        OCStackResult factoryReset(std::shared_ptr< OCResource > resource,
+                DiagnosticsCallback callback);
+
+        /**
+         * API to show a list of supported diagnostics units
+         * Callback call when a response arrives.
+         *
+         * @return the list in JSON format
+         */
+        std::string getListOfSupportedDiagnosticsUnits();
+
+    private:
+
+        GroupManager *g_groupmanager;
+
+        std::vector< DiagnosticsUnitInfo > DiagnosticsUnitTable;
+
+        void onExecuteForGroupAction(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+        void onGetChildInfoForUpdate(const HeaderOptions& headerOptions,
+                const OCRepresentation& rep, const int eCode, std::string conf);
+        void onCreateActionSet(const HeaderOptions& headerOptions, const OCRepresentation& rep,
+                const int eCode, std::string conf);
+        void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode,
+                std::string conf);
+        void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode,
+                std::string conf);
+
+        std::shared_ptr< OCResource > getResource(std::string conf);
+        DiagnosticsCallback getCallback(std::string conf);
+        std::string getUpdateVal(std::string conf);
+        std::string getAttributeByDiagnosticsName(DiagnosticsName name);
+        std::string getUriByDiagnosticsName(DiagnosticsName name);
+
+        std::string getHostFromURI(std::string oldUri);
+
+        bool isSimpleResource(std::shared_ptr< OCResource > resource);
+
+    };
+}
+#endif  /* __OC_THINGSCONFIGURATION__*/
diff --git a/service/things-manager/sdk/src/ThingsManager.cpp b/service/things-manager/sdk/src/ThingsManager.cpp
new file mode 100644 (file)
index 0000000..a65b987
--- /dev/null
@@ -0,0 +1,188 @@
+//******************************************************************
+//
+// Copyright 2014 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/// @file    ThingsManager.cpp
+
+#include "ThingsManager.h"
+#include "GroupManager.h"
+#include "GroupSynchronization.h"
+#include "ThingsConfiguration.h"
+#include "ThingsDiagnostics.h"
+#include <algorithm>
+#include <thread>
+
+using namespace OC;
+namespace OIC
+{
+
+    GroupManager *g_groupManager;
+    GroupSynchronization *g_groupSync = NULL;
+    ThingsConfiguration *g_thingsConf = NULL;
+    ThingsDiagnostics *g_thingsDiag = NULL;
+
+    ThingsManager::ThingsManager(void)
+    {
+        g_groupManager = new GroupManager();
+        g_groupSync = GroupSynchronization::getInstance();
+        g_thingsConf = ThingsConfiguration::getInstance();
+        g_thingsDiag = ThingsDiagnostics::getInstance();
+        g_thingsConf->setGroupManager(g_groupManager);
+        g_thingsDiag->setGroupManager(g_groupManager);
+    }
+
+    /**
+     * Virtual destructor
+     */
+    ThingsManager::~ThingsManager(void)
+    {
+        delete g_groupManager;
+        g_groupSync->deleteInstance();
+        g_thingsConf->deleteInstance();
+        g_thingsDiag->deleteInstance();
+    }
+
+    OCStackResult ThingsManager::findCandidateResources(std::vector< std::string > resourceTypes,
+            std::function< void(std::vector< std::shared_ptr< OCResource > >) > callback,
+            int waitsec)
+    {
+        OCStackResult result = g_groupManager->findCandidateResources(resourceTypes, callback,
+                waitsec);
+
+        return result;
+    }
+
+    OCStackResult ThingsManager::subscribeCollectionPresence(std::shared_ptr< OCResource > resource,
+            std::function< void(std::string, OCStackResult) > callback)
+    {
+        OCStackResult result = g_groupManager->subscribeCollectionPresence(resource, callback);
+
+        return result;
+    }
+
+    OCStackResult ThingsManager::findGroup(std::vector< std::string > collectionResourceTypes,
+            FindCallback callback)
+    {
+        OCStackResult result = g_groupSync->findGroup(collectionResourceTypes, callback);
+
+        return result;
+    }
+
+    OCStackResult ThingsManager::createGroup(std::string collectionResourceType)
+    {
+        OCStackResult result = g_groupSync->createGroup(collectionResourceType);
+
+        return result;
+    }
+
+    OCStackResult ThingsManager::joinGroup(std::string collectionResourceType,
+            OCResourceHandle resourceHandle)
+    {
+        OCStackResult result = g_groupSync->joinGroup(collectionResourceType, resourceHandle);
+
+        return result;
+    }
+
+    OCStackResult ThingsManager::joinGroup(const std::shared_ptr< OCResource > resource,
+            OCResourceHandle resourceHandle)
+    {
+        OCStackResult result = g_groupSync->joinGroup(resource, resourceHandle);
+
+        return result;
+    }
+
+    OCStackResult ThingsManager::leaveGroup(std::string collectionResourceType,
+            OCResourceHandle resourceHandle)
+    {
+        OCStackResult result = g_groupSync->leaveGroup(collectionResourceType, resourceHandle);
+
+        return result;
+    }
+
+    void ThingsManager::deleteGroup(std::string collectionResourceType)
+    {
+        g_groupSync->deleteGroup(collectionResourceType);
+    }
+
+    std::map< std::string, OCResourceHandle > ThingsManager::getGroupList()
+    {
+        return g_groupSync->getGroupList();
+    }
+
+    OCStackResult ThingsManager::updateConfigurations(std::shared_ptr< OCResource > resource,
+            std::map< ConfigurationName, ConfigurationValue > configurations,
+            ConfigurationCallback callback)
+    {
+        return g_thingsConf->updateConfigurations(resource, configurations, callback);
+    }
+    OCStackResult ThingsManager::getConfigurations(std::shared_ptr< OCResource > resource,
+            std::vector< ConfigurationName > configurations, ConfigurationCallback callback)
+    {
+        return g_thingsConf->getConfigurations(resource, configurations, callback);
+    }
+    std::string ThingsManager::getListOfSupportedConfigurationUnits()
+    {
+        return g_thingsConf->getListOfSupportedConfigurationUnits();
+    }
+
+    OCStackResult ThingsManager::doBootstrap(ConfigurationCallback callback)
+    {
+        return g_thingsConf->doBootstrap(callback);
+    }
+
+    OCStackResult ThingsManager::reboot(std::shared_ptr< OCResource > resource,
+            ConfigurationCallback callback)
+    {
+        return g_thingsDiag->reboot(resource, callback);
+    }
+    OCStackResult ThingsManager::factoryReset(std::shared_ptr< OCResource > resource,
+            ConfigurationCallback callback)
+    {
+        return g_thingsDiag->factoryReset(resource, callback);
+    }
+
+    std::string ThingsManager::getStringFromActionSet(const ActionSet *newActionSet)
+    {
+        return g_groupManager->getStringFromActionSet(newActionSet);
+    }
+    ActionSet* ThingsManager::getActionSetfromString(std::string desc)
+    {
+        return g_groupManager->getActionSetfromString(desc);
+    }
+    OCStackResult ThingsManager::addActionSet(std::shared_ptr< OCResource > resource,
+            const ActionSet* newActionSet, PutCallback cb)
+    {
+        return g_groupManager->addActionSet(resource, newActionSet, cb);
+    }
+    OCStackResult ThingsManager::executeActionSet(std::shared_ptr< OCResource > resource,
+            std::string actionsetName, PostCallback cb)
+    {
+        return g_groupManager->executeActionSet(resource, actionsetName, cb);
+    }
+    OCStackResult ThingsManager::getActionSet(std::shared_ptr< OCResource > resource,
+            std::string actionsetName, GetCallback cb)
+    {
+        return g_groupManager->getActionSet(resource, actionsetName, cb);
+    }
+    OCStackResult ThingsManager::deleteActionSet(std::shared_ptr< OCResource > resource,
+            std::string actionsetName, PostCallback cb)
+    {
+        return g_groupManager->deleteActionSet(resource, actionsetName, cb);
+    }
+}