Imported Upstream version 1.0.1 upstream/1.0.1
authorYoungjae Shin <yj99.shin@samsung.com>
Mon, 4 Jan 2016 06:26:00 +0000 (15:26 +0900)
committerYoungjae Shin <yj99.shin@samsung.com>
Mon, 4 Jan 2016 06:26:00 +0000 (15:26 +0900)
171 files changed:
Readme.scons.txt
android/android_api/base/jni/JniCaInterface.c
android/android_api/base/jni/JniOcPlatform.cpp
android/android_api/base/jni/JniOcRepresentation.cpp
android/android_api/base/jni/JniOcRepresentation.h
android/android_api/base/jni/JniOcResource.cpp
android/android_api/base/jni/JniOcResource.h
android/android_api/base/jni/JniOnObserveListener.cpp
android/android_api/base/src/main/java/org/iotivity/base/OcPlatform.java
android/android_api/base/src/main/java/org/iotivity/base/OcRepresentation.java
android/android_api/base/src/main/java/org/iotivity/base/OcResource.java
build_common/SConscript
examples/OICMiddle/SConscript
examples/OICSensorBoard/Makefile
extlibs/tinydtls/README_Iotivity [new file with mode: 0644]
extlibs/tinydtls/SConscript
extlibs/tinydtls/crypto.c
extlibs/tinydtls/crypto.h
extlibs/tinydtls/dtls.c
extlibs/tinydtls/tests/dtls-client.c
resource/c_common/SConscript
resource/c_common/ocrandom/include/ocrandom.h [moved from resource/csdk/ocrandom/include/ocrandom.h with 100% similarity]
resource/c_common/ocrandom/src/ocrandom.c [moved from resource/csdk/ocrandom/src/ocrandom.c with 96% similarity]
resource/c_common/ocrandom/test/SConscript [moved from resource/csdk/ocrandom/test/SConscript with 97% similarity]
resource/c_common/ocrandom/test/android/randomtest.cpp [moved from resource/csdk/ocrandom/test/android/randomtest.cpp with 100% similarity]
resource/c_common/ocrandom/test/arduino/randomtest.cpp [moved from resource/csdk/ocrandom/test/arduino/randomtest.cpp with 100% similarity]
resource/c_common/ocrandom/test/linux/randomtest.cpp [moved from resource/csdk/ocrandom/test/linux/randomtest.cpp with 100% similarity]
resource/csdk/SConscript
resource/csdk/connectivity/SConscript
resource/csdk/connectivity/build/SConscript
resource/csdk/connectivity/build/tizen/SConscript
resource/csdk/connectivity/build/tizen/gbsbuild.sh
resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec
resource/csdk/connectivity/build/tizen/scons/SConscript
resource/csdk/connectivity/common/inc/logger.h
resource/csdk/connectivity/common/src/caremotehandler.c
resource/csdk/connectivity/common/src/ulinklist.c
resource/csdk/connectivity/inc/caadapterutils.h
resource/csdk/connectivity/inc/cablockwisetransfer.h
resource/csdk/connectivity/lib/libcoap-4.1.1/SConscript
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h
resource/csdk/connectivity/samples/android/casample/sampleService/src/main/jni/ResourceModel.c
resource/csdk/connectivity/samples/linux/sample_main.c
resource/csdk/connectivity/samples/tizen/casample.c
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/cablockwisetransfer.c
resource/csdk/connectivity/src/caconnectivitymanager.c
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/tcp_adapter/SConscript
resource/csdk/connectivity/src/tcp_adapter/catcpserver.c
resource/csdk/doc/Doxyfile
resource/csdk/routing/SConscript
resource/csdk/routing/src/routingtablemanager.c
resource/csdk/routing/src/routingutility.c
resource/csdk/security/SConscript
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/ck_manager/sample/SConscript
resource/csdk/security/provisioning/src/pmutility.c [changed mode: 0644->0755]
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/credresource.c
resource/csdk/stack/include/ocpayload.h [changed mode: 0755->0644]
resource/csdk/stack/include/octypes.h
resource/csdk/stack/include/payload_logging.h
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp
resource/csdk/stack/src/ocpayload.c
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c
resource/csdk/stack/src/ocresource.c
resource/csdk/stack/src/ocserverrequest.c
resource/csdk/stack/src/ocstack.c
resource/csdk/stack/src/oicgroup.c
resource/csdk/stack/src/rdpayload.c
resource/csdk/stack/test/SConscript
resource/examples/SConscript
resource/include/OCRepresentation.h
resource/include/OCSerialization.h
resource/src/InProcClientWrapper.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/SConscript
resource/unit_tests.scons
resource/unittests/OCRepresentationEncodingTest.cpp
resource/unittests/OCRepresentationTest.cpp
resource/unittests/SConscript
service/resource-container/examples/BMISensorBundle/include/BMISensorResource.h
service/resource-container/examples/BMISensorBundle/src/BMISensorBundleActivator.cpp
service/resource-container/examples/ContainerSample.cpp
service/resource-container/examples/ContainerSampleClient.cpp
service/resource-container/examples/DiscomfortIndexSensorBundle/include/DiscomfortIndexSensorResource.h
service/resource-container/examples/DiscomfortIndexSensorBundle/src/DISensorBundleActivator.cpp
service/resource-container/examples/DiscomfortIndexSensorBundle/src/DiscomfortIndexSensorResource.cpp
service/resource-container/examples/HueSampleBundle/src/HueSampleBundleActivator.cpp
service/resource-container/examples/tizen/ContainerClientApp/.cproject
service/resource-container/examples/tizen/ContainerClientApp/src/clientmain.cpp
service/resource-container/examples/tizen/ContainerClientApp/src/containerclient.cpp
service/resource-container/examples/tizen/ContainerServerApp/.cproject
service/resource-container/examples/tizen/ContainerServerApp/inc/container.h
service/resource-container/examples/tizen/ContainerServerApp/inc/rcmain.h
service/resource-container/examples/tizen/ContainerServerApp/src/container.cpp
service/resource-container/examples/tizen/ContainerServerApp/src/rcmain.cpp
service/resource-container/src/DiscoverResourceUnit.h
service/resource-directory/src/internal/rd_storage.c
service/resource-directory/src/internal/rd_storage.h
service/resource-directory/src/rd_client.c
service/resource-directory/src/rd_server.c
service/resource-encapsulation/android/service/src/main/jni/JniRcsResourceObject.cpp
service/resource-encapsulation/examples/linux/SampleResourceClient.cpp [changed mode: 0755->0644]
service/resource-encapsulation/examples/linux/SampleResourceServer.cpp [changed mode: 0755->0644]
service/resource-encapsulation/examples/tizen/RESampleClientApp/inc/reclient.h
service/resource-encapsulation/examples/tizen/RESampleClientApp/inc/reclientmain.h
service/resource-encapsulation/examples/tizen/RESampleClientApp/src/reclient.cpp
service/resource-encapsulation/examples/tizen/RESampleClientApp/src/reclientmain.cpp
service/resource-encapsulation/examples/tizen/RESampleServerApp/inc/remain.h
service/resource-encapsulation/examples/tizen/RESampleServerApp/inc/reserver.h
service/resource-encapsulation/examples/tizen/RESampleServerApp/src/remain.cpp
service/resource-encapsulation/examples/tizen/RESampleServerApp/src/reserver.cpp
service/resource-encapsulation/src/common/primitiveResource/include/PrimitiveResource.h
service/resource-encapsulation/src/common/primitiveResource/include/PrimitiveResourceImpl.h
service/resource-encapsulation/src/common/primitiveResource/unittests/PrimitiveResourceTest.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSResourceObject.cpp
service/simulator/SConscript [changed mode: 0755->0644]
service/simulator/examples/server/service_provider.cpp
service/simulator/inc/simulator_resource_model.h
service/simulator/inc/simulator_resource_server.h
service/simulator/java/eclipse-plugin/ClientControllerPlugin/META-INF/MANIFEST.MF
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/manager/ResourceManager.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/FindResourcePage.java
service/simulator/java/eclipse-plugin/ClientControllerPlugin/src/oic/simulator/clientcontroller/view/dialogs/PostRequestDialog.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ImageManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/manager/ResourceManager.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/utils/Constants.java
service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/view/dialogs/DeleteResourcePage.java
service/simulator/java/jni/resource_attributes_jni.cpp
service/simulator/java/jni/simulator_common_jni.h
service/simulator/java/jni/simulator_device_info_jni.cpp
service/simulator/java/jni/simulator_manager_jni.cpp
service/simulator/java/jni/simulator_remote_resource_jni.cpp
service/simulator/java/jni/simulator_remote_resource_jni.h
service/simulator/java/jni/simulator_resource_model_jni.cpp
service/simulator/java/jni/simulator_resource_server_jni.cpp
service/simulator/java/jni/simulator_resource_server_jni.h
service/simulator/java/sdk/src/org/oic/simulator/SimulatorResourceModel.java
service/simulator/java/sdk/src/org/oic/simulator/clientcontroller/SimulatorRemoteResource.java
service/simulator/java/sdk/src/org/oic/simulator/serviceprovider/SimulatorResourceServer.java
service/simulator/ramlparser/raml/jsonSchemaParser/Definitions.h
service/simulator/ramlparser/raml/jsonSchemaParser/Items.h
service/simulator/src/client-controller/attribute_generator.cpp
service/simulator/src/client-controller/attribute_generator.h
service/simulator/src/client-controller/put_request_generator.cpp
service/simulator/src/client-controller/simulator_remote_resource_impl.cpp
service/simulator/src/common/simulator_resource_model.cpp
service/simulator/src/service-provider/resource_update_automation.cpp
service/simulator/src/service-provider/resource_update_automation.h
service/simulator/src/service-provider/simulator_resource_server_impl.cpp
service/simulator/src/service-provider/simulator_resource_server_impl.h
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/clientcontroller/test/SimulatorRemoteResourceTest.java
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/serviceprovider/test/SimlatorResourceServerTest.java
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorManagerTest.java
service/simulator/unittests/SimulatorTest/src/org/oic/simulator/test/SimulatorResourceModelTest.java
service/things-manager/sampleapp/tizen/TMSampleApp/src/configuration.cpp
service/things-manager/sdk/src/ThingsConfiguration.cpp
service/third_party_libs.scons
tools/darwin/mkfwk_ios.sh
tools/darwin/mkfwk_osx.sh
tools/tizen/iotivity.spec

index bc0c411..aac7c90 100644 (file)
@@ -133,39 +133,137 @@ tool isn't installed. An message will be displayed, please follow the message
 to skip it.
 
 
-=== Build IoTivity project on Linux(Ubuntu) ===
+=== Build IoTivity project ===
 
-1. Build IoTivity project for Linux
-      $ cd <top directory of the project>
-      $ sudo apt-get install libboost-dev libexpat1-dev libboost-thread-dev libssl-dev
-      $ scons
+Linux:
+ * Possible values for <TARGET_TRANSPORT> are: ALL, IP, BLE
 
-2. Build IoTivity project for Android
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard. To see all of its
-allowed value, please execute command 'scons TARGET_OS=android -Q -h')
-
-3. Build IoTivity project for Arduino
-      $ cd <top directory of the project>
-      $ sudo apt-get install dos2unix
-      $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy SHIELD=zzz
-(xxx can be avr, arm; yyy is the name of the board, zzz is the shield type, to
-get allowed values run: scons TARGET_OS=arduino TARGET_ARCH=xxx SHIELD=zzz -h.
-You may see a option 'CPU' in the output of above command line, that's due to
-some boards have different processors, to specify the processor, add 'CPU=zzz'
-in the command line. If no 'CPU' option exists, that means the board only
-support one kind of processor, it's unnecessary to specify it)
+1. Go to root directory
+    $ cd <top directory of the project>
+    $ sudo apt-get install libboost-dev libboost-thread-dev libssl-dev libtool
+
+2. Execute following command(s) to start build based on transport selection required
+
+    -> Building for all transports :
+    $ scons TARGET_OS=linux TARGET_TRANSPORT=ALL
+
+    -> Building for a specific transport :
+    $ scons TARGET_OS=linux TARGET_TRANSPORT=IP
+
+    -> Building for multiple transports :
+    $ scons TARGET_OS=linux TARGET_TRANSPORT=IP,BLE TARGET_ARCH=xxx
+
+    -> Clean Build (all transports) :
+    $ scons TARGET_OS=linux TARGET_TRANSPORT=ALL -c (for clean)
+
+Android:
+ * Possible values for <TARGET_TRANSPORT> are: ALL, IP, BT, BLE
+ * Possible values for <TARGET_ARCH> are: x86, armeabi, armeabi-v7a, armeabi-v7a-hard
+   (To see all of its allowed value, please execute command 'scons TARGET_OS=android -Q -h')
+
+1. Go to root directory
+    $ cd <top directory of the project>
+
+2. Execute following command(s) to start build based on transport selection required
+
+    -> Building for all transports :
+    $ scons TARGET_OS=android TARGET_TRANSPORT=ALL TARGET_ARCH=xxx
+
+    -> Building for a specific transport :
+    $ scons TARGET_OS=android TARGET_TRANSPORT=IP TARGET_ARCH=xxx
+
+    -> Building for multiple transports :
+    $ scons TARGET_OS=android TARGET_TRANSPORT=IP,BT,BLE TARGET_ARCH=xxx
+
+    -> Clean Build (all transports) :
+    $ scons TARGET_OS=android TARGET_TRANSPORT=ALL -c (for clean)
+
+Tizen:
+ * Possible values for <TARGET_TRANSPORT> are: ALL, IP, BT, BLE
+
+ 1. Go to root directory
+    $ cd <top directory of the project>
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+    -> Building for all transports :
+    $ scons TARGET_OS=tizen TARGET_TRANSPORT=ALL
+
+    -> Building for a specific transport :
+    $ scons TARGET_OS=tizen TARGET_TRANSPORT=IP
+
+    -> Building for multiple transports :
+    $ scons TARGET_OS=tizen TARGET_TRANSPORT=IP,BT,BLE TARGET_ARCH=xxx
+
+    -> Clean Build (all transports) :
+    $ scons TARGET_OS=tizen TARGET_TRANSPORT=ALL -c (for clean)
 
-4. Build Iotivity project for Tizen
-      $ cd <top directory of the project>
-      $ sh gbsbuild.sh
 (we provide the spec file required by gbs tool at toools/tizen directory.
 gbs is default build tool for Tizen platfrom, we can refer the following
 wiki to setup Tizen development environment:
 https://source.tizen.org/documentation/developer-guide/getting-started-guide)
 
-Note: Currently most IoTivity project doesn't support Windows, so you can't set
+Arduino:
+ * Possible values for <TARGET_TRANSPORT> are: IP, BLE
+ * Possible values for <TARGET_ARCH> are: arv, arm
+    (arv: arduino due, arm: arduino mega)
+ * Possible values for <BOARD> are: arduino_due_x_dbg, arduino_due_x, mega
+ * Possible values for <SHIELD> are: ETH, WIFI
+    (It is required in the case of the arduino due.)
+
+ 1. Go to root directory
+    $ cd <top directory of the project>
+    $ sudo apt-get install dos2unix
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+    -> Building for a specific transport :
+    $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy SHIELD=zzz
+
+(To get allowed values run: scons TARGET_OS=arduino TARGET_ARCH=xxx SHIELD=zzz -h.
+You may see a option 'CPU' in the output of above command line, that's due to
+some boards have different processors, to specify the processor, add 'CPU=zzz'
+in the command line. If no 'CPU' option exists, that means the board only
+support one kind of processor, it's unnecessary to specify it)
+
+Mac OSX:
+ * Possible values for <SYS_VERSION> are: OSX version, e.g. 10.9
+
+ 1. Go to root directory
+    $ cd <top directory of the project>
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+    -> Building for a specific transport :
+    $ scons SYS_VERSION=yyy
+
+IOS:
+ * Possible values for <TARGET_ARCH> are: i386, x86_64, armv7, armv7s, arm64
+ * Possible values for <SYS_VERSION> are: IOS version, e.g. 7.0
+
+ 1. Go to root directory
+    $ cd <top directory of the project>
+
+ 2. Execute following command(s) to start build based on transport selection required
+
+    -> Building for a specific transport :
+    $ scons TARGET_OS=ios TARGET_ARCH=xxx SYS_VERSION=yyy
+
+* Additional options
+ * VERBOSE=true or false (Show compilation)
+ * RELEASE=true or false (Build for release?)
+ * LOGGING=true or false (Enable stack logging)
+ * SECURED=1 or 0 (Build with DTLS)
+ * TEST=1 or 0 (Run unit tests)
+ * SECURED=1 or 0 (Build with DTLS)
+ * BUILD_SAMPLE=ON or OFF (Build with sample)
+ * ROUTING=GW or EP (Enable routing)
+ * WITH_TCP=true or false (Enable CoAP over TCP Transport, arduino is not supported)
+ * WITH_RA=true or false (Build with Remote Access module)
+ * WITH_RD=1 or 0 (Build including Resource Directory)
+ * SIMULATOR=true or false (Build with simulator module)
+
+Note1: Currently most IoTivity project doesn't support Windows, so you can't set
 TARGET_OS to 'windows' except the project support Windows.
 
 That's to say if the project doesn't support Windows, run:
@@ -174,25 +272,7 @@ or run on Windows
       $ scons
 may always fail.
 
-
-=== Build IoTivity project on Mac OSX ===
-
-1. Build IoTivity project for Mac OSX
-      $ cd <top directory of the project>
-      $ scons SYS_VERSION=yyy
-(yyy is the OSX version, e.g. 10.9)
-
-2. Build IoTivity project for Android(It's the same as on Ubuntu)
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=android TARGET_ARCH=xxx
-(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard)
-
-3. Build IoTivity project for IOS
-      $ cd <top directory of the project>
-      $ scons TARGET_OS=ios TARGET_ARCH=xxx SYS_VERSION=yyy
-(xxx can be i386, x86_64, armv7, armv7s, arm64, yyy is IOS version, e.g. 7.0)
-
-Note:
+Note2:
 1) for convenience, a script (auto_build.sh) is provided to run possible build
 at once. Following is the usage:
 
index eb1e07a..0972278 100644 (file)
@@ -50,11 +50,4 @@ Java_org_iotivity_ca_CaInterface_initialize
     LOGI("CaInterface_initialize");
 
     CANativeJNISetContext(env, context);
-
-    CAResult_t res = CAInitialize();
-
-    if (CA_STATUS_OK != res)
-    {
-        LOGE("Could not Initialize");
-    }
 }
\ No newline at end of file
index e3a6cd5..93029c9 100644 (file)
@@ -347,6 +347,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_configure
     {
         port = static_cast<uint16_t>(jPort);
     }
+
     PlatformConfig cfg{
         JniUtils::getServiceType(env, jServiceType),
         JniUtils::getModeType(env, jModeType),
@@ -355,7 +356,6 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_configure
         JniUtils::getQOS(env, static_cast<int>(jQOS)),
         JniOcSecurity::getOCPersistentStorage()
     };
-
     OCPlatform::Configure(cfg);
 }
 
@@ -392,7 +392,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers0
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -433,7 +433,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyAllObservers1
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -506,7 +506,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyListOfObservers2(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -581,7 +581,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_notifyListOfObservers3(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -639,7 +639,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -698,7 +698,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_findResource1(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -755,7 +755,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDeviceInfo0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -814,7 +814,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getDeviceInfo1(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -871,7 +871,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getPlatformInfo0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -930,7 +930,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_getPlatformInfo1(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -966,7 +966,7 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_registerResource0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
         return nullptr;
     }
     JniOcResourceHandle* jniHandle = new JniOcResourceHandle(resourceHandle);
@@ -1045,7 +1045,7 @@ jobject jListener, jint jResourceProperty)
     {
         LOGE("%s", e.reason().c_str());
         delete entityHandler;
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
         return nullptr;
     }
 
@@ -1106,7 +1106,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerDeviceInfo0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1237,7 +1237,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_registerPlatformInfo0(
         catch (OCException& e)
         {
             LOGE("Error is due to %s", e.reason().c_str());
-            ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+            ThrowOcException(e.code(), e.reason().c_str());
         }
 }
 
@@ -1274,7 +1274,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unregisterResource0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1323,7 +1323,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResource0
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1395,7 +1395,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindResources0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1450,7 +1450,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unbindResource0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1521,7 +1521,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unbindResources0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1567,7 +1567,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindTypeToResource0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1613,7 +1613,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_bindInterfaceToResource
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1639,7 +1639,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_startPresence0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1665,7 +1665,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_stopPresence0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1720,7 +1720,7 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_subscribePresence0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
         return nullptr;
     }
 
@@ -1794,7 +1794,7 @@ JNIEXPORT jobject JNICALL Java_org_iotivity_base_OcPlatform_subscribePresence1(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
         return nullptr;
     }
 
@@ -1853,7 +1853,7 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_unsubscribePresence0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
 
@@ -1965,6 +1965,6 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcPlatform_sendResponse0(
     catch (OCException& e)
     {
         LOGE("%s", e.reason().c_str());
-        ThrowOcException(OC_STACK_ERROR, e.reason().c_str());
+        ThrowOcException(e.code(), e.reason().c_str());
     }
 }
index 3c69be6..c3c37ad 100644 (file)
@@ -793,6 +793,22 @@ JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getUri
 
 /*
 * Class:     org_iotivity_base_OcRepresentation
+* Method:    getHost
+* Signature: ()Ljava/lang/String;
+*/
+JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getHost
+(JNIEnv *env, jobject thiz)
+{
+    LOGD("OcRepresentation_getHost");
+    OCRepresentation *rep = JniOcRepresentation::getOCRepresentationPtr(env, thiz);
+    if (!rep) return nullptr;
+
+    std::string uri(rep->getHost());
+    return env->NewStringUTF(uri.c_str());
+}
+
+/*
+* Class:     org_iotivity_base_OcRepresentation
 * Method:    setUri
 * Signature: (Ljava/lang/String;)V
 */
index 2ac86ff..ee8f222 100644 (file)
@@ -653,6 +653,14 @@ extern "C" {
 
     /*
     * Class:     org_iotivity_base_OcRepresentation
+    * Method:    getHost
+    * Signature: ()Ljava/lang/String;
+    */
+    JNIEXPORT jstring JNICALL Java_org_iotivity_base_OcRepresentation_getHost
+        (JNIEnv *, jobject);
+
+    /*
+    * Class:     org_iotivity_base_OcRepresentation
     * Method:    setUri
     * Signature: (Ljava/lang/String;)V
     */
index f8b8977..4d15fe0 100644 (file)
@@ -284,17 +284,12 @@ OCStackResult JniOcResource::observe(JNIEnv* env, ObserveType observeType,
     return m_sharedResource->observe(observeType, queryParametersMap, observeCallback, QoS);
 }
 
-OCStackResult JniOcResource::cancelObserve(JNIEnv* env)
-{
-    this->m_onObserveManager.removeAllListeners(env);
-    return m_sharedResource->cancelObserve();
-}
-
 OCStackResult JniOcResource::cancelObserve(JNIEnv* env, QualityOfService qos)
 {
-    //TODO confirm behavior
-    //add removal of java listeners by qos
-    this->m_onObserveManager.removeAllListeners(env);
+    if (QualityOfService::HighQos != qos)
+    {
+        this->m_onObserveManager.removeAllListeners(env);
+    }
     return m_sharedResource->cancelObserve(qos);
 }
 
@@ -1279,34 +1274,6 @@ jobject jListener, jint jQoS)
 
 /*
 * Class:     org_iotivity_base_OcResource
-* Method:    cancelObserve
-* Signature: ()V
-*/
-JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve
-(JNIEnv *env, jobject thiz)
-{
-    LOGD("OcResource_cancelObserve");
-    JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
-    if (!resource) return;
-
-    try
-    {
-        OCStackResult result = resource->cancelObserve(env);
-
-        if (OC_STACK_OK != result)
-        {
-            ThrowOcException(result, "OcResource_cancelObserve");
-        }
-    }
-    catch (OCException& e)
-    {
-        LOGE("%s", e.reason().c_str());
-        ThrowOcException(e.code(), e.reason().c_str());
-    }
-}
-
-/*
-* Class:     org_iotivity_base_OcResource
 * Method:    cancelObserve1
 * Signature: I)V
 */
@@ -1518,4 +1485,4 @@ JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_dispose
     LOGD("OcResource_dispose");
     JniOcResource *resource = JniOcResource::getJniOcResourcePtr(env, thiz);
     delete resource;
-}
\ No newline at end of file
+}
index cb36691..a038312 100644 (file)
@@ -251,14 +251,6 @@ extern "C" {
 
     /*
     * Class:     org_iotivity_base_OcResource
-    * Method:    cancelObserve
-    * Signature: ()V
-    */
-    JNIEXPORT void JNICALL Java_org_iotivity_base_OcResource_cancelObserve
-        (JNIEnv *, jobject);
-
-    /*
-    * Class:     org_iotivity_base_OcResource
     * Method:    cancelObserve1
     * Signature: (I)V
     */
index 0b2c28f..3ad1d11 100644 (file)
@@ -127,6 +127,11 @@ void JniOnObserveListener::onObserveCallback(const HeaderOptions headerOptions,
             m_ownerResource->removeOnObserveListener(env, m_jwListener);
             env->Throw((jthrowable)ex);
         }
+
+        if (OC_OBSERVE_DEREGISTER == sequenceNumber)
+        {
+            checkExAndRemoveListener(env);
+        }
     }
 
     if (JNI_EDETACHED == envRet) g_jvm->DetachCurrentThread();
index 5b2388d..8733878 100644 (file)
@@ -70,6 +70,7 @@ public final class OcPlatform {
     public static final String PRESENCE_URI = "/oic/ad";
 
     private static volatile boolean sIsPlatformInitialized = false;
+    private static QualityOfService sPlatformQualityOfService = QualityOfService.NA;
 
     private OcPlatform() {
     }
@@ -86,6 +87,8 @@ public final class OcPlatform {
         if (!sIsPlatformInitialized) {
             CaInterface.initialize(platformConfig.getContext());
 
+            sPlatformQualityOfService = platformConfig.getQualityOfService();
+
             OcPlatform.configure(
                     platformConfig.getServiceType().getValue(),
                     platformConfig.getModeType().getValue(),
@@ -463,7 +466,7 @@ public final class OcPlatform {
 
     /**
      * This API registers a resource with the server
-     * <P>
+     * <p/>
      * Note: This API applies to server & client side.
      * </P>
      *
@@ -482,9 +485,10 @@ public final class OcPlatform {
 
     /**
      * This API registers a resource with the server NOTE: This API applies to server side only.
-     * <P>
+     * <p/>
      * Note: This API applies to server side only.
      * </P>
+     *
      * @param resourceUri         The URI of the resource. Example: "a/light"
      * @param resourceTypeName    The resource type. Example: "light"
      * @param resourceInterface   The resource interface (whether it is collection etc).
@@ -933,4 +937,14 @@ public final class OcPlatform {
                     "OcPlatform.Configure before any other API calls are permitted");
         }
     }
+
+    /**
+     * Gets platform quality of service
+     *
+     * @return quality of service
+     */
+    public static QualityOfService getPlatformQualityOfService() {
+        OcPlatform.initCheck();
+        return sPlatformQualityOfService;
+    }
 }
index eba1001..309ab70 100644 (file)
@@ -278,6 +278,8 @@ public class OcRepresentation {
 
     public native String getUri();
 
+    public native String getHost();
+
     public native void setUri(String uri);
 
     /**
index 333c5b2..bb22465 100644 (file)
@@ -411,7 +411,9 @@ public class OcResource {
      *
      * @throws OcException
      */
-    public native void cancelObserve() throws OcException;
+    public void cancelObserve() throws OcException{
+        this.cancelObserve(OcPlatform.getPlatformQualityOfService());
+    }
 
     /**
      * Method to cancel the observation on the resource
index d808228..a73adab 100644 (file)
@@ -70,7 +70,7 @@ else:
 ######################################################################
 # Common build options (release, target os, target arch)
 ######################################################################
-targets_disallow_multitransport = ['arduino', 'android']
+targets_disallow_multitransport = ['arduino']
 
 help_vars = Variables()
 help_vars.Add(BoolVariable('VERBOSE', 'Show compilation', False))
index 6748493..8c1152d 100644 (file)
@@ -34,7 +34,7 @@ examples_env = lib_env.Clone()
 examples_env.AppendUnique(CPPPATH = [
                '../../resource/include/',
                '../../resource/csdk/stack/include',
-               '../../resource/csdk/ocrandom/include',
+               '../../resource/c_common/ocrandom/include',
                '../../resource/csdk/logger/include',
                '../../resource/oc_logger/include'
                ])
index 8a6939b..ab12e21 100644 (file)
@@ -7,7 +7,7 @@ YOCTOCXXFLAGS=-I$(SDKTARGETSYSROOT)/usr/include/iotivity/resource/ -I$(SDKTARGET
 
 YOCTOLDFLAGS=-loc -loctbstack -loc_logger -lmraa
 
-CXXFLAGS=-I../../resource/include -I../../resource/csdk/stack/include -I../../resource/csdk/ocrandom/include -I../../resource/csdk/logger/include -I../../resource/oc_logger/include
+CXXFLAGS=-I../../resource/include -I../../resource/csdk/stack/include -I../../resource/c_common/ocrandom/include -I../../resource/csdk/logger/include -I../../resource/oc_logger/include
 
 LDFLAGS=-L../../out/linux/$(CLIENTARCH)/$(BUILDTYPE) -loc -loctbstack -loc_logger
 
diff --git a/extlibs/tinydtls/README_Iotivity b/extlibs/tinydtls/README_Iotivity
new file mode 100644 (file)
index 0000000..3d18404
--- /dev/null
@@ -0,0 +1,26 @@
+SUPPORTED CIPHER-SUITES
+  TLS_PSK_WITH_AES_128_CCM_8(0xC0A8)
+  TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8(0xC0AE)
+  TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256(0xC037)
+  TLS_ECDH_anon_WITH_AES_128_CBC_SHA256(0xC018)
+
+TEST APPLICATIONS
+These applications can be build from Iotivity's root directory using below commands:
+scons extlibs/tinydtls/dtls-client SECURED=1 RELEASE=0
+scons extlibs/tinydtls/dtls-server SECURED=1 RELEASE=0
+
+
+INTER-OPERABILITY TESTING
+tinyDTLS's cipher-suite implementations can be verified for compatibility against other
+SSL libraries.
+Use below commands to perform compatibility testing against mBed SSL library.
+./ssl_server2 debug_level=5 dtls=1 psk=73656372657450534b psk_identity=Client_identity \
+    force_version=dtls1_2 force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256
+./dtls-client -v 6 -c 4 localhost 4433
+
+./ssl_client2 debug_level=5 dtls=1 psk=73656372657450534b psk_identity=Client_identity \
+    force_version=dtls1_2 force_ciphersuite=TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256
+./dtls-server -v 6 localhost -p 4433
+
+Above commands can also be tested with TLS-PSK-WITH-AES-128-CCM-8 cipher suite.
+
index 1f3c2a7..64d5d08 100644 (file)
@@ -68,7 +68,7 @@ if not env.get('RELEASE'):
 else:
        env.AppendUnique(CPPDEFINES = ['NDEBUG'])
 
-env.AppendUnique(CPPDEFINES = ['DTLSV12',  'WITH_SHA256', 'DTLS_CHECK_CONTENTTYPE'])
+env.AppendUnique(CPPDEFINES = ['DTLSV12',  'WITH_SHA256', 'DTLS_CHECK_CONTENTTYPE', 'SHA2_USE_INTTYPES_H'])
 
 
 libtinydtls = env.StaticLibrary('libtinydtls', env.get('TINYDTLS_SRC'), OBJPREFIX='libtinydtls_')
index 77a8e04..de07f49 100644 (file)
@@ -330,7 +330,7 @@ dtls_ccm_decrypt(aes128_t *ccm_ctx, const unsigned char *src,
 
 static size_t
 dtls_cbc_encrypt(aes128_t *aes_ctx,
-                 unsigned char *key, size_t keylen,
+                 unsigned char *mac_key, size_t mac_keylen,
                  const unsigned char *iv,
                  const unsigned char *src, size_t srclen,
                  unsigned char *buf) {
@@ -349,7 +349,7 @@ dtls_cbc_encrypt(aes128_t *aes_ctx,
     dtls_hdr = src - DTLS_CBC_IV_LENGTH - sizeof(dtls_record_header_t);
 
     //Calculate MAC : Append the MAC code to end of content
-    hmac_ctx = dtls_hmac_new(key, keylen);
+    hmac_ctx = dtls_hmac_new(mac_key, mac_keylen);
     dtls_mac(hmac_ctx,
              dtls_hdr,
              src, srclen,
@@ -389,7 +389,7 @@ dtls_cbc_encrypt(aes128_t *aes_ctx,
 
 static size_t
 dtls_cbc_decrypt(aes128_t *aes_ctx,
-                 unsigned char *key, size_t keylen,
+                 unsigned char *mac_key, size_t mac_keylen,
                  const unsigned char *iv,
                  const unsigned char *src, size_t srclen,
                  unsigned char *buf) {
@@ -403,6 +403,7 @@ dtls_cbc_decrypt(aes128_t *aes_ctx,
     int i, j;
     int blocks;
     int depaddinglen = 0;
+    uint8_t wrongpadding_flag = 0;
     dtls_hmac_context_t* hmac_ctx = NULL;
 
     pos = buf;
@@ -429,8 +430,19 @@ dtls_cbc_decrypt(aes128_t *aes_ctx,
     //de-padding
     depaddinglen = buf[srclen -1];
 
+    /**
+     * message validation check in case of wrong key.
+     * In case of wrong padding legnth was detected
+     * set depadding length to zero in order to resist the padding oracle attack
+     * and prevent invalid memory access.
+     */
+    if(srclen <= DTLS_HMAC_DIGEST_SIZE + depaddinglen + 1) {
+        depaddinglen = 0;
+        wrongpadding_flag = 1;
+    }
+
     //Calculate MAC
-    hmac_ctx = dtls_hmac_new(key, keylen);
+    hmac_ctx = dtls_hmac_new(mac_key, mac_keylen);
     if(!hmac_ctx) {
         return -1;
     }
@@ -449,7 +461,7 @@ dtls_cbc_decrypt(aes128_t *aes_ctx,
     //verify the MAC
     if(memcmp(mac_buf,
               buf + (srclen - DTLS_HMAC_DIGEST_SIZE - depaddinglen - 1),
-              DTLS_HMAC_DIGEST_SIZE) != 0)
+              DTLS_HMAC_DIGEST_SIZE) != 0 || wrongpadding_flag)
     {
         dtls_crit("Failed to verification of MAC\n");
         return -1;
@@ -702,7 +714,8 @@ int
 dtls_encrypt(const unsigned char *src, size_t length,
             unsigned char *buf,
             unsigned char *nounce,
-            unsigned char *key, size_t keylen,
+            unsigned char *write_key, size_t write_keylen,
+            unsigned char *mac_key, size_t mac_keylen,
             const unsigned char *aad, size_t la,
             const dtls_cipher_t cipher)
 {
@@ -711,7 +724,7 @@ dtls_encrypt(const unsigned char *src, size_t length,
 
   if(cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ||
      cipher == TLS_PSK_WITH_AES_128_CCM_8) {
-      ret = rijndael_set_key_enc_only(&ctx->data.ctx, key, 8 * keylen);
+      ret = rijndael_set_key_enc_only(&ctx->data.ctx, write_key, 8 * write_keylen);
       if (ret < 0) {
         /* cleanup everything in case the key has the wrong size */
         dtls_warn("cannot set rijndael key\n");
@@ -724,7 +737,7 @@ dtls_encrypt(const unsigned char *src, size_t length,
   }
   if(cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 ||
      cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256) {
-      ret = rijndael_set_key(&ctx->data.ctx, key, 8 * keylen);
+      ret = rijndael_set_key(&ctx->data.ctx, write_key, 8 * write_keylen);
       if (ret < 0) {
         /* cleanup everything in case the key has the wrong size */
         dtls_warn("cannot set rijndael key\n");
@@ -733,7 +746,7 @@ dtls_encrypt(const unsigned char *src, size_t length,
 
       if (src != buf)
         memmove(buf, src, length);
-      ret = dtls_cbc_encrypt(&ctx->data, key, keylen, nounce, src, length, buf);
+      ret = dtls_cbc_encrypt(&ctx->data, mac_key, mac_keylen, nounce, src, length, buf);
   }
 
 error:
@@ -745,7 +758,8 @@ int
 dtls_decrypt(const unsigned char *src, size_t length,
             unsigned char *buf,
             unsigned char *nounce,
-            unsigned char *key, size_t keylen,
+            unsigned char *read_key, size_t read_keylen,
+            unsigned char *mac_key, size_t mac_keylen,
             const unsigned char *aad, size_t la,
             const dtls_cipher_t cipher)
 {
@@ -754,7 +768,7 @@ dtls_decrypt(const unsigned char *src, size_t length,
 
   if(cipher == TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ||
      cipher == TLS_PSK_WITH_AES_128_CCM_8) {
-      ret = rijndael_set_key_enc_only(&ctx->data.ctx, key, 8 * keylen);
+      ret = rijndael_set_key_enc_only(&ctx->data.ctx, read_key, 8 * read_keylen);
       if (ret < 0) {
         /* cleanup everything in case the key has the wrong size */
         dtls_warn("cannot set rijndael key\n");
@@ -768,7 +782,7 @@ dtls_decrypt(const unsigned char *src, size_t length,
 
   if(cipher == TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 ||
      cipher == TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256) {
-      ret = rijndael_set_key(&ctx->data.ctx, key, 8 * keylen);
+      ret = rijndael_set_key(&ctx->data.ctx, read_key, 8 * read_keylen);
       if (ret < 0) {
         /* cleanup everything in case the key has the wrong size */
         dtls_warn("cannot set rijndael key\n");
@@ -777,7 +791,7 @@ dtls_decrypt(const unsigned char *src, size_t length,
 
       if (src != buf)
         memmove(buf, src, length);
-      ret = dtls_cbc_decrypt(&ctx->data, key, keylen, nounce, src, length, buf);
+      ret = dtls_cbc_decrypt(&ctx->data, mac_key, mac_keylen, nounce, src, length, buf);
     }
 
 error:
index e101a11..8ea83f2 100644 (file)
 #include "ecc/ecc.h"
 
 /* TLS_PSK_WITH_AES_128_CCM_8 */
-#define DTLS_MAC_KEY_LENGTH    0
+#define DTLS_CCM_MAC_KEY_LENGTH        0       /* MAC Key length for AES-CCM cipher suites */
+#define DTLS_CBC_MAC_KEY_LENGTH       32       /* MAC Key length for AES-CBC Cipher suites */
 #define DTLS_KEY_LENGTH        16 /* AES-128 */
 #define DTLS_BLK_LENGTH        16 /* AES-128 */
 #define DTLS_MAC_LENGTH        DTLS_HMAC_DIGEST_SIZE
-#define DTLS_IV_LENGTH         4  /* length of nonce_explicit */
+#define DTLS_CCM_IV_LENGTH     4  /* length of nonce_explicit */
 #define DTLS_CBC_IV_LENGTH     16
 
 /** 
  * be large enough to hold the pre_master_secret, i.e. twice the length of the 
  * pre-shared key + 1.
  */
+#define CCM_KB_LENGTH  \
+    (2 * DTLS_KEY_LENGTH + 2 * DTLS_CCM_IV_LENGTH)
+
+#define CBC_KB_LENGTH  \
+    (2 * DTLS_CBC_MAC_KEY_LENGTH + 2 * DTLS_KEY_LENGTH )
+
 #define MAX_KEYBLOCK_LENGTH  \
-  (2 * DTLS_MAC_KEY_LENGTH + 2 * DTLS_KEY_LENGTH + 2 * DTLS_IV_LENGTH)
+    ((CCM_KB_LENGTH) > (CBC_KB_LENGTH) ? (CCM_KB_LENGTH) : (CBC_KB_LENGTH) )
 
 /** Length of DTLS master_secret */
 #define DTLS_MASTER_SECRET_LENGTH 48
@@ -151,9 +158,59 @@ typedef struct {
 /* The following macros provide access to the components of the
  * key_block in the security parameters. */
 
+static inline int dtls_kb_mac_secret_size(dtls_cipher_t cipher)
+{
+    switch(cipher)
+    {
+        case TLS_NULL_WITH_NULL_NULL:
+
+            return 0;
+            break;
+
+        case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
+        case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
+
+            return DTLS_CBC_MAC_KEY_LENGTH;
+            break;
+
+        case TLS_PSK_WITH_AES_128_CCM_8:
+        case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
+
+            return DTLS_CCM_MAC_KEY_LENGTH;
+            break;
+    }
+
+    return -1;
+}
+
+
+static inline int dtls_kb_iv_size(dtls_cipher_t cipher)
+{
+    switch(cipher)
+    {
+        case TLS_NULL_WITH_NULL_NULL:
+        case TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256:
+        case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256:
+
+            return 0;
+            break;
+
+        case TLS_PSK_WITH_AES_128_CCM_8:
+        case TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
+
+            return DTLS_CCM_IV_LENGTH;
+            break;
+    }
+
+    return -1;
+}
+
+
+
+
 #define dtls_kb_client_mac_secret(Param, Role) ((Param)->key_block)
 #define dtls_kb_server_mac_secret(Param, Role)                         \
-  (dtls_kb_client_mac_secret(Param, Role) + DTLS_MAC_KEY_LENGTH)
+  (dtls_kb_client_mac_secret(Param, Role) + dtls_kb_mac_secret_size((Param)->cipher))
 #define dtls_kb_remote_mac_secret(Param, Role)                         \
   ((Role) == DTLS_SERVER                                               \
    ? dtls_kb_client_mac_secret(Param, Role)                            \
@@ -162,9 +219,8 @@ typedef struct {
   ((Role) == DTLS_CLIENT                                               \
    ? dtls_kb_client_mac_secret(Param, Role)                            \
    : dtls_kb_server_mac_secret(Param, Role))
-#define dtls_kb_mac_secret_size(Param, Role) DTLS_MAC_KEY_LENGTH
 #define dtls_kb_client_write_key(Param, Role)                          \
-  (dtls_kb_server_mac_secret(Param, Role) + DTLS_MAC_KEY_LENGTH)
+  (dtls_kb_server_mac_secret(Param, Role) + dtls_kb_mac_secret_size((Param)->cipher))
 #define dtls_kb_server_write_key(Param, Role)                          \
   (dtls_kb_client_write_key(Param, Role) + DTLS_KEY_LENGTH)
 #define dtls_kb_remote_write_key(Param, Role)                          \
@@ -179,7 +235,7 @@ typedef struct {
 #define dtls_kb_client_iv(Param, Role)                                 \
   (dtls_kb_server_write_key(Param, Role) + DTLS_KEY_LENGTH)
 #define dtls_kb_server_iv(Param, Role)                                 \
-  (dtls_kb_client_iv(Param, Role) + DTLS_IV_LENGTH)
+  (dtls_kb_client_iv(Param, Role) + dtls_kb_iv_size((Param)->cipher))
 #define dtls_kb_remote_iv(Param, Role)                                 \
   ((Role) == DTLS_SERVER                                               \
    ? dtls_kb_client_iv(Param, Role)                                    \
@@ -188,11 +244,10 @@ typedef struct {
   ((Role) == DTLS_CLIENT                                               \
    ? dtls_kb_client_iv(Param, Role)                                    \
    : dtls_kb_server_iv(Param, Role))
-#define dtls_kb_iv_size(Param, Role) DTLS_IV_LENGTH
 
 #define dtls_kb_size(Param, Role)                                      \
-  (2 * (dtls_kb_mac_secret_size(Param, Role) +                         \
-       dtls_kb_key_size(Param, Role) + dtls_kb_iv_size(Param, Role)))
+  (2 * (dtls_kb_mac_secret_size((Param)->cipher) +                     \
+       dtls_kb_key_size(Param, Role) + dtls_kb_iv_size((Param)->cipher)))
 
 /* just for consistency */
 #define dtls_kb_digest_size(Param, Role) DTLS_MAC_LENGTH
@@ -275,7 +330,8 @@ void dtls_mac(dtls_hmac_context_t *hmac_ctx,
 int dtls_encrypt(const unsigned char *src, size_t length,
                 unsigned char *buf,
                 unsigned char *nounce,
-                unsigned char *key, size_t keylen,
+                unsigned char *write_key, size_t write_keylen,
+                unsigned char *mac_key, size_t mac_keylen,
                 const unsigned char *aad, size_t aad_length,
                 const dtls_cipher_t cipher);
 
@@ -300,7 +356,8 @@ int dtls_encrypt(const unsigned char *src, size_t length,
 int dtls_decrypt(const unsigned char *src, size_t length,
                 unsigned char *buf,
                 unsigned char *nounce,
-                unsigned char *key, size_t keylen,
+                unsigned char *read_key, size_t read_keylen,
+                unsigned char *mac_key, size_t mac_keylen,
                 const unsigned char *a_data, size_t a_data_length,
                 const dtls_cipher_t cipher);
 
index 7815c66..2869aca 100644 (file)
@@ -660,11 +660,11 @@ static void dtls_debug_keyblock(dtls_security_parameters_t *config)
   dtls_debug("key_block (%d bytes):\n", dtls_kb_size(config, peer->role));
   dtls_debug_dump("  client_MAC_secret",
                  dtls_kb_client_mac_secret(config, peer->role),
-                 dtls_kb_mac_secret_size(config, peer->role));
+                 dtls_kb_mac_secret_size(config->cipher));
 
   dtls_debug_dump("  server_MAC_secret",
                  dtls_kb_server_mac_secret(config, peer->role),
-                 dtls_kb_mac_secret_size(config, peer->role));
+                 dtls_kb_mac_secret_size(config->cipher));
 
   dtls_debug_dump("  client_write_key",
                  dtls_kb_client_write_key(config, peer->role),
@@ -676,11 +676,11 @@ static void dtls_debug_keyblock(dtls_security_parameters_t *config)
 
   dtls_debug_dump("  client_IV",
                  dtls_kb_client_iv(config, peer->role),
-                 dtls_kb_iv_size(config, peer->role));
+                 dtls_kb_iv_size(config->cipher));
 
   dtls_debug_dump("  server_IV",
                  dtls_kb_server_iv(config, peer->role),
-                 dtls_kb_iv_size(config, peer->role));
+                 dtls_kb_iv_size(config->cipher));
 }
 
 /** returns the name of the goven handshake type number.
@@ -835,6 +835,9 @@ calculate_key_block(dtls_context_t *ctx,
   /* create key_block from master_secret
    * key_block = PRF(master_secret,
                     "key expansion" + tmp.random.server + tmp.random.client) */
+  security->cipher = handshake->cipher;
+  security->compression = handshake->compression;
+  security->rseq = 0;
 
   dtls_prf(master_secret,
           DTLS_MASTER_SECRET_LENGTH,
@@ -847,9 +850,6 @@ calculate_key_block(dtls_context_t *ctx,
   memcpy(handshake->tmp.master_secret, master_secret, DTLS_MASTER_SECRET_LENGTH);
   dtls_debug_keyblock(security);
 
-  security->cipher = handshake->cipher;
-  security->compression = handshake->compression;
-  security->rseq = 0;
 
   return 0;
 }
@@ -1471,6 +1471,8 @@ dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
                start + DTLS_CBC_IV_LENGTH, nonce,
                dtls_kb_local_write_key(security, peer->role),
                dtls_kb_key_size(security, peer->role),
+               dtls_kb_local_mac_secret(security, peer->role),
+               dtls_kb_mac_secret_size(security->cipher),
                NULL, 0,
                security->cipher);
      if (res < 0)
@@ -1553,8 +1555,8 @@ dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
 
     memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
     memcpy(nonce, dtls_kb_local_iv(security, peer->role),
-        dtls_kb_iv_size(security, peer->role));
-    memcpy(nonce + dtls_kb_iv_size(security, peer->role), start, 8); /* epoch + seq_num */
+        dtls_kb_iv_size(security->cipher));
+    memcpy(nonce + dtls_kb_iv_size(security->cipher), start, 8); /* epoch + seq_num */
 
     dtls_debug_dump("nonce:", nonce, DTLS_CCM_BLOCKSIZE);
     dtls_debug_dump("key:", dtls_kb_local_write_key(security, peer->role),
@@ -1572,6 +1574,8 @@ dtls_prepare_record(dtls_peer_t *peer, dtls_security_parameters_t *security,
     res = dtls_encrypt(start + 8, res - 8, start + 8, nonce,
                dtls_kb_local_write_key(security, peer->role),
                dtls_kb_key_size(security, peer->role),
+               dtls_kb_local_mac_secret(security, peer->role),
+               dtls_kb_mac_secret_size(security->cipher),
                A_DATA, A_DATA_LEN,
                security->cipher);
 
@@ -2815,8 +2819,8 @@ dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
                        uint8 cookie[], size_t cookie_length) {
   uint8 buf[DTLS_CH_LENGTH_MAX];
   uint8 *p = buf;
-  uint8_t cipher_size;
-  uint8_t extension_size;
+  uint8_t cipher_size = 0;
+  uint8_t extension_size = 0;
   int psk = 0;
   int ecdsa = 0;
   int ecdh_anon = 0;
@@ -2850,7 +2854,13 @@ dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
    }
 
   cipher_size = 2 + ((ecdsa || x509) ? 2 : 0) + (psk ? 2 : 0) + (ecdh_anon ? 2 : 0) + (ecdhe_psk ? 2 : 0);
-  extension_size = (ecdsa || x509) ? (2 + 6 + 6 + 8 + 6) : 0;
+
+  /* Is extension needed? */
+  extension_size = (ecdsa || x509 || ecdhe_psk || ecdh_anon) ? 2 : 0;
+  /* Supported EC and Supported Point Formats */
+  extension_size += (ecdsa || x509 || ecdhe_psk | ecdh_anon) ? ( 8 + 6) : 0;
+  /* Supported Client and Server Cert Types */
+  extension_size += (ecdsa || x509) ? ( 6 + 6) : 0;
 
   if (cipher_size == 0) {
     dtls_crit("no cipher callbacks implemented\n");
@@ -2944,7 +2954,7 @@ dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
 
     p += sizeof(uint8);
 
-    /* client certificate type extension */
+    /* server certificate type extension */
     dtls_int_to_uint16(p, TLS_EXT_SERVER_CERTIFICATE_TYPE);
     p += sizeof(uint16);
 
@@ -2964,7 +2974,9 @@ dtls_send_client_hello(dtls_context_t *ctx, dtls_peer_t *peer,
       dtls_int_to_uint8(p, TLS_CERT_TYPE_RAW_PUBLIC_KEY);
 
     p += sizeof(uint8);
+  }
 
+  if (ecdsa || x509 || ecdhe_psk || ecdh_anon ) {
     /* elliptic_curves */
     dtls_int_to_uint16(p, TLS_EXT_ELLIPTIC_CURVES);
     p += sizeof(uint16);
@@ -3646,6 +3658,8 @@ decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
     clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
                       dtls_kb_remote_write_key(security, peer->role),
                       dtls_kb_key_size(security, peer->role),
+                       dtls_kb_remote_mac_secret(security, peer->role),
+                       dtls_kb_mac_secret_size(security->cipher),
                       NULL, 0,
                       security->cipher);
 
@@ -3663,10 +3677,10 @@ decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
 
     memset(nonce, 0, DTLS_CCM_BLOCKSIZE);
     memcpy(nonce, dtls_kb_remote_iv(security, peer->role),
-        dtls_kb_iv_size(security, peer->role));
+        dtls_kb_iv_size(security->cipher));
 
     /* read epoch and seq_num from message */
-    memcpy(nonce + dtls_kb_iv_size(security, peer->role), *cleartext, 8);
+    memcpy(nonce + dtls_kb_iv_size(security->cipher), *cleartext, 8);
     *cleartext += 8;
     clen -= 8;
 
@@ -3687,6 +3701,8 @@ decrypt_verify(dtls_peer_t *peer, uint8 *packet, size_t length,
     clen = dtls_decrypt(*cleartext, clen, *cleartext, nonce,
                       dtls_kb_remote_write_key(security, peer->role),
                       dtls_kb_key_size(security, peer->role),
+                       dtls_kb_remote_mac_secret(security, peer->role),
+                       dtls_kb_mac_secret_size(security->cipher),
                       A_DATA, A_DATA_LEN,
                       security->cipher);
   }
index 2c4eff9..279d91a 100644 (file)
@@ -252,9 +252,9 @@ get_psk_info(struct dtls_context_t *ctx UNUSED_PARAM,
     return psk_client_id_length;
   case DTLS_PSK_KEY:
     if (id_len != psk_server_id_length || memcmp(psk_server_id, id, id_len) != 0) {
-      dtls_warn("PSK for unknown id requested, exiting\n");
-      return dtls_alert_fatal_create(DTLS_ALERT_ILLEGAL_PARAMETER);
-    } else if (result_length < psk_key_length) {
+      dtls_debug("PSK for unknown id requested\n");
+    }
+    if (result_length < psk_key_length) {
       dtls_warn("cannot set psk -- buffer too small\n");
       return dtls_alert_fatal_create(DTLS_ALERT_INTERNAL_ERROR);
     }
index d018d88..9bb80dc 100644 (file)
 Import('env')
 import os
 
+target_os = env.get('TARGET_OS')
+
 env.AppendUnique(CPPPATH = [
             os.path.join(Dir('.').abspath),
             os.path.join(Dir('.').abspath, 'oic_malloc/include'),
-            os.path.join(Dir('.').abspath, 'oic_string/include')
+            os.path.join(Dir('.').abspath, 'oic_string/include'),
+            os.path.join(Dir('.').abspath, 'ocrandom/include')
         ])
 
-if env.get('TARGET_OS') == 'tizen':
+if target_os == 'tizen':
        env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 else:
        env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource/c_common')])
 
-env.AppendUnique(LIBS = ['c_common'])
+if target_os in ['tizen', 'linux']:
+       env.ParseConfig("pkg-config --cflags --libs uuid")
+
+env.PrependUnique(LIBS = ['c_common'])
 
 common_env = env.Clone()
 
@@ -45,9 +51,10 @@ common_env = env.Clone()
 # Source files and Targets
 ######################################################################
 common_src = [
-    'oic_string/src/oic_string.c',
-    'oic_malloc/src/oic_malloc.c'
-    ]
+       'oic_string/src/oic_string.c',
+       'oic_malloc/src/oic_malloc.c',
+       'ocrandom/src/ocrandom.c',
+       ]
 
 commonlib = common_env.StaticLibrary('c_common', common_src)
 common_env.InstallTarget(commonlib, 'c_common')
similarity index 96%
rename from resource/csdk/ocrandom/src/ocrandom.c
rename to resource/c_common/ocrandom/src/ocrandom.c
index debbee1..ff09112 100644 (file)
 #ifdef ARDUINO
 #include "Arduino.h"
 
+// ARM GCC compiler doesnt define srandom function.
+#if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
+#define HAVE_SRANDOM 1
+#endif
+
 uint8_t GetRandomBitRaw()
 {
     return analogRead((uint8_t)ANALOG_IN) & 0x1;
@@ -143,7 +148,11 @@ int8_t OCSeedRandom()
     {
         result += result + GetRandomBit();
     }
-    randomSeed(result);
+#if HAVE_SRANDOM
+    srandom(result);
+#else
+    srand(result);
+#endif
     return 0;
 #endif
 
@@ -173,7 +182,11 @@ uint8_t OCGetRandomByte(void)
 #if defined(__ANDROID__) || defined(__linux__) || defined(__APPLE__)
     return rand() & 0x00FF;
 #elif defined ARDUINO
-    return random(256) & 0x00FF;
+#ifdef HAVE_SRANDOM
+    return random() & 0x00FF;
+#else
+    return rand() & 0x00FF;
+#endif
 #endif
 }
 
similarity index 97%
rename from resource/csdk/ocrandom/test/SConscript
rename to resource/c_common/ocrandom/test/SConscript
index 2e7bc52..86e08a1 100644 (file)
@@ -63,4 +63,4 @@ if env.get('TEST') == '1':
                 from tools.scons.RunTest import *
                 run_test(randomtest_env,
                          'resource_csdk_random_test.memcheck',
-                         'resource/csdk/ocrandom/test/randomtests')
+                         'resource/c_common/ocrandom/test/randomtests')
index df647b8..fbbad61 100644 (file)
@@ -43,7 +43,6 @@ liboctbstack_env.PrependUnique(CPPPATH = [
                '../../extlibs/cjson/',
                '../../extlibs/timer/',
                'logger/include',
-               'ocrandom/include',
                'stack/include',
                'stack/include/internal',
                '../oc_logger/include',
@@ -79,8 +78,8 @@ if target_os in ['android', 'linux', 'tizen']:
 
 liboctbstack_env.AppendUnique(LIBS = ['coap', 'm'])
 
-if target_os == 'tizen':
-    liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
+if target_os in ['tizen', 'linux']:
+       liboctbstack_env.ParseConfig("pkg-config --cflags --libs uuid")
 
 if target_os not in ['android', 'arduino', 'windows', 'winrt']:
        liboctbstack_env.AppendUnique(LIBS = ['pthread'])
@@ -128,7 +127,6 @@ liboctbstack_src = [
        OCTBSTACK_SRC + 'occollection.c',
        OCTBSTACK_SRC + 'oicgroup.c',
        'logger/src/logger.c',
-       'ocrandom/src/ocrandom.c',
        OCTBSTACK_SRC + "rdpayload.c"
        ]
 
index 0e37d4b..5de9342 100644 (file)
@@ -60,7 +60,7 @@ else:
                env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER'])
 
        if with_tcp == True:
-               if target_os in['linux']:
+               if target_os in ['linux', 'tizen']:
                        env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER'])
                        print "CA Transport is TCP"
                else:
index 045faab..953f3f3 100644 (file)
@@ -60,12 +60,13 @@ help_vars = Variables()
 help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug
 help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False))
 help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host]))
-help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP', 'TCP']))
+help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP']))
 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
 help_vars.Add(EnumVariable('ROUTING', 'Enable routing', 'EP', allowed_values=('GW', 'EP')))
 help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
+help_vars.Add(BoolVariable('WITH_TCP', 'Enable TCP', False))
 
 help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
 
index c8c105c..57a4e90 100644 (file)
@@ -12,12 +12,13 @@ buildsample = env.get('BUILD_SAMPLE')
 release_mode = env.get('RELEASE')
 secured = env.get('SECURED')
 logging = env.get('LOGGING')
+with_tcp = env.get('WITH_TCP')
 
 print "Given Transport is %s" % transport
 print "Given OS is %s" % target_os
 
 if target_os == 'tizen':
-       command = "sh resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging)
+       command = "sh resource/csdk/connectivity/build/tizen/gbsbuild.sh %s %s %s %s %s %s" % (transport, secured, buildsample, release_mode, logging, with_tcp)
        print "Created Command is %s" % command
        gbs_script = env.Command('gbs_build', None, command)
        AlwaysBuild ('gbs_script')
\ No newline at end of file
index ac2ba58..6ab0e87 100755 (executable)
@@ -25,8 +25,12 @@ export RELEASE=$4
 echo $5
 export LOGGING=$5
 
+echo $6
+export WITH_TCP=$6
+
 echo $TARGET_TRANSPORT
 echo $BUILD_SAMPLE
+echo $WITH_TCP
 
 rm -rf $name-$version
 
@@ -90,7 +94,7 @@ if [ ! -d .git ]; then
 fi
 
 echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l --include-all  --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5'"
+gbscommand="gbs build -A armv7l --include-all  --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'WITH_TCP $6'"
 echo $gbscommand
 if eval $gbscommand; then
    echo "Core build is successful"
index 1602200..8c3a25b 100644 (file)
@@ -20,6 +20,7 @@ BuildRequires: boost-thread
 BuildRequires: boost-system
 BuildRequires: boost-filesystem
 BuildRequires: scons
+BuildRequires: pkgconfig(uuid)
 
 
 %description
@@ -34,7 +35,7 @@ SLP oicca application
 echo %{ROOTDIR}
 
 scons TARGET_OS=tizen -c
-scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING}
+scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} SECURED=%{SECURED} RELEASE=%{RELEASE} LOGGING=%{LOGGING} WITH_TCP=%{WITH_TCP}
 
 %install
 mkdir -p %{DEST_INC_DIR}
index 9a9644d..a06d5ee 100644 (file)
@@ -7,6 +7,7 @@ Import('env')
 
 target_os = env.get('TARGET_OS')
 transport = env.get('TARGET_TRANSPORT')
+with_tcp = env.get('WITH_TCP')
 
 print "Given Transport is %s" % transport
 
@@ -41,6 +42,12 @@ else:
        else:
                env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER'])
 
+       if with_tcp == True:
+               env.AppendUnique(CPPDEFINES = ['TCP_ADAPTER'])
+               print "CA Transport is TCP"
+       else:
+               env.AppendUnique(CPPDEFINES = ['NO_TCP_ADAPTER'])
+
 
 env.SConscript(['../con/lib/libcoap-4.1.1/SConscript'])
 env.SConscript(['../con/SConscript'])
index e48ee7c..558b1c5 100644 (file)
@@ -179,8 +179,6 @@ void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
 #define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)
 #else // These macros are defined for Linux, Android, and Arduino
 #define OIC_LOG_INIT()    OICLogInit()
-#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
-    OICLogBuffer((level), (tag), (buffer), (bufferSize))
 
 #ifdef ARDUINO
 #define OIC_LOG_CONFIG(ctx)
@@ -189,11 +187,15 @@ void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
 #define OIC_LOG_V(level, tag, ...)
 // To enable OIC_LOG_V, uncomment the below
 //#define OIC_LOG_V(level, tag, format, ...)  OICLogv((level), PCF(tag), __LINE__, PCF(format), __VA_ARGS__)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
+    OICLogBuffer((level), PCF(tag), (buffer), (bufferSize))
 #else
 #define OIC_LOG_CONFIG(ctx)    OICLogConfig((ctx))
 #define OIC_LOG_SHUTDOWN()     OICLogShutdown()
 #define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), (logStr))
 #define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
+#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)\
+    OICLogBuffer((level), tag, (buffer), (bufferSize))
 #endif //ARDUINO
 #endif //__TIZEN__
 #else //TB_LOG
@@ -211,4 +213,4 @@ void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
 #ifdef __cplusplus
 }
 #endif // __cplusplus
-#endif /* U_LOGGER_H_ */
\ No newline at end of file
+#endif /* U_LOGGER_H_ */
index a39b7d4..1315dae 100644 (file)
@@ -55,6 +55,20 @@ CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
         return NULL;
     }
 
+    // check the method type of request info.
+    // Keep this check in sync with CAMethod_t
+    switch (rep->method)
+    {
+        case CA_GET:
+        case CA_POST:
+        case CA_PUT:
+        case CA_DELETE:
+            break;
+        default:
+            OIC_LOG_V(ERROR, TAG, "Method %u is invalid", rep->method);
+            return NULL;
+    }
+
     // allocate the request info structure.
     CARequestInfo_t *clone = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
     if (!clone)
index e75c49f..e796f4b 100644 (file)
@@ -124,6 +124,8 @@ CAResult_t u_linklist_free(u_linklist_t **linklist)
 
         (*linklist)->size -= 1;
     }
+
+    OICFree(*linklist);
     *linklist=NULL;
 
     return CA_STATUS_OK;
index 7c9611b..d146678 100644 (file)
@@ -212,13 +212,16 @@ void CAClearNetInterfaceInfoList(u_arraylist_t *infoList);
  */
 void CAClearServerInfoList(u_arraylist_t *serverInfoList);
 
+#ifndef WITH_ARDUINO
 /**
  * Convert address from binary to string.
- * @param[in]    ipaddr   IP address info.
- * @param[out]   host     address string (must be CA_IPADDR_SIZE).
- * @param[out]   port     host order port number.
+ * @param[in]    sockAddr     IP address info.
+ * @param[in]    sockAddrLen  size of sockAddr.
+ * @param[out]   host         address string (must be CA_IPADDR_SIZE).
+ * @param[out]   port         host order port number.
  */
-void CAConvertAddrToName(const struct sockaddr_storage *sockaddr, char *host, uint16_t *port);
+void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sockAddrLen,
+                         char *host, uint16_t *port);
 
 /**
  * Convert address from string to binary.
@@ -227,6 +230,7 @@ void CAConvertAddrToName(const struct sockaddr_storage *sockaddr, char *host, ui
  * @param[out]  ipaddr    IP address info.
  */
 void CAConvertNameToAddr(const char *host, uint16_t port, struct sockaddr_storage *sockaddr);
+#endif /* WITH_ARDUINO */
 
 #ifdef __ANDROID__
 /**
index 49461f8..3b2878b 100644 (file)
@@ -329,16 +329,24 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
                              const CABlockDataID_t *blockID, coap_list_t **options);
 
 /**
- * Add the block option in pdu data.
- * @param[in]   pdu    pdu object.
+ * Add the block option in option list.
  * @param[out]  block    block data.
  * @param[in]   blockType   block option type.
+ * @param[out]  options   option list.
  * @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
  */
-CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType,
+CAResult_t CAAddBlockOptionImpl(coap_block_t *block, uint8_t blockType,
                                 coap_list_t **options);
 
 /**
+ * Add the option list in pdu data.
+ * @param[out]  pdu    pdu object.
+ * @param[out]  options   option list.
+ * @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAAddOptionToPDU(coap_pdu_t *pdu, coap_list_t **options);
+
+/**
  * Add the size option in pdu data.
  * @param[in/out]   pdu    pdu object.
  * @param[in]   sizeType    size option type.
index ded6fd0..876bc03 100644 (file)
@@ -37,7 +37,7 @@ if target_os not in ['windows', 'winrt']:
        libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections',
                        '-fdata-sections', '-fno-exceptions'])
 
-if target_os == 'linux':
+if target_os in ['linux', 'tizen']:
        if with_tcp == True:
                libcoap_env.AppendUnique(CPPDEFINES = ['WITH_TCP'])
 
index 175394b..e4f40d6 100644 (file)
@@ -330,6 +330,9 @@ unsigned int coap_get_length_from_header(const unsigned char *header, coap_trans
     unsigned int length_field_data = 0;
     switch(transport)
     {
+        case coap_tcp:
+            length = header[0] >> 4;
+            break;
         case coap_tcp_8bit:
             length = header[1] + COAP_TCP_LENGTH_FIELD_8_BIT;
             break;
index 87f6044..1e19c85 100644 (file)
@@ -194,7 +194,7 @@ typedef enum
 #ifdef WORDS_BIGENDIAN
 typedef union
 {
-    typedef struct
+    struct
     {
         unsigned int version:2; /* protocol version */
         unsigned int type:2; /* type flag */
index 9e032ee..5e08bb4 100644 (file)
@@ -597,7 +597,13 @@ Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj
 
     CAResponseInfo_t responseInfo = { 0 };
 
-    if (msgType != CA_MSG_RESET)
+    if (CA_MSG_RESET == msgType ||
+        (CA_MSG_ACKNOWLEDGE == msgType && CA_EMPTY == responseValue))
+    {
+        printf("RESET or ACK/EMPTY. there will be not payload/option\n");
+        responseInfo.result = CA_EMPTY;
+    }
+    else
     {
         responseData.token = g_clientToken;
         responseData.tokenLength = g_clientTokenLength;
@@ -607,23 +613,18 @@ Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj
         {
             uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
             responseData.payload = (CAPayload_t) malloc(length);
-            sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
-                    g_localSecurePort);
+            snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
+                     g_resourceUri, g_localSecurePort);
             responseData.payloadSize = length;
         }
         else
         {
             uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
             responseData.payload = (CAPayload_t) malloc(length);
-            sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
+            snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, g_resourceUri);
             responseData.payloadSize = length;
         }
     }
-    //msgType is RESET
-    else
-    {
-        responseInfo.result = CA_EMPTY;
-    }
 
     responseInfo.info = responseData;
 
@@ -642,6 +643,7 @@ Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj
     // destroy remote endpoint
     CADestroyEndpoint(g_clientEndpoint);
     g_clientEndpoint = NULL;
+    free(responseData.payload);
 }
 
 JNIEXPORT void JNICALL
@@ -743,7 +745,8 @@ Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject
             free(requestData.resourceUri);
             return;
         }
-        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
+        snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
+                 resourceURI, g_localSecurePort);
         requestData.payloadSize = length;
     }
     else
@@ -861,12 +864,12 @@ Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, job
         {
             char networkInfo[NETWORK_INFO_LENGTH];
             LOGI("Type: %d", tempInfo[index].adapter);
-            sprintf(networkInfo, "%d",tempInfo[index].adapter);
+            snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].adapter);
             callback("Type :", networkInfo);
             if (CA_ADAPTER_IP == tempInfo[index].adapter)
             {
                 LOGI("Port: %d", tempInfo[index].port);
-                sprintf(networkInfo, "%d",tempInfo[index].port);
+                snprintf(networkInfo, NETWORK_INFO_LENGTH, "%d",tempInfo[index].port);
                 callback("Port: ", networkInfo);
             }
             LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
@@ -979,7 +982,7 @@ void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestI
         free(g_remoteAddress);
 
         char portInfo[PORT_LENGTH] = { 0, };
-        sprintf(portInfo, "%d", object->port);
+        snprintf(portInfo, PORT_LENGTH, "%d", object->port);
         callback("Remote Port: ", portInfo);
 
         //clone g_clientEndpoint
@@ -1070,9 +1073,10 @@ void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestI
             if (NULL != g_responseListenerObject)
             {
                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
-                sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
-                        requestInfo->info.options[i].optionID,
-                        requestInfo->info.options[i].optionLength);
+                snprintf(optionInfo, OPTION_INFO_LENGTH,
+                         "Num[%d] - ID : %d, Option Length : %d", i + 1,
+                         requestInfo->info.options[i].optionID,
+                         requestInfo->info.options[i].optionLength);
 
                 callback("Option info: ", optionInfo);
 
@@ -1177,7 +1181,7 @@ void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* respon
         free(g_remoteAddress);
 
         char portInfo[PORT_LENGTH] = { 0, };
-        sprintf(portInfo, "%d", object->port);
+        snprintf(portInfo, PORT_LENGTH, "%d", object->port);
         callback("Remote Port: ", portInfo);
 
         if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
@@ -1219,9 +1223,10 @@ void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* respon
             if (NULL != g_responseListenerObject)
             {
                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
-                sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
-                        responseInfo->info.options[i].optionID,
-                        responseInfo->info.options[i].optionLength);
+                snprintf(optionInfo, OPTION_INFO_LENGTH,
+                         "Num[%d] - ID : %d, Option Length : %d", i + 1,
+                         responseInfo->info.options[i].optionID,
+                         responseInfo->info.options[i].optionLength);
 
                 callback("Option info: ", optionInfo);
 
@@ -1641,6 +1646,12 @@ bool read_file(const char* name, char** bytes, size_t* length)
     // Get file length
     fseek(file, 0, SEEK_END);
     fileLen = ftell(file);
+    if (-1 == fileLen)
+    {
+        fprintf(stderr, "Failed to read file length");
+        fclose(file);
+        return false;
+    }
     fseek(file, 0, SEEK_SET);
 
     LOGI("file size: %d", fileLen);
@@ -1693,7 +1704,7 @@ void saveFile(const char *payload, size_t payloadSize)
     char* path = calloc(1, sizeof(char) * path_length);
     if (path != NULL)
     {
-        sprintf(path, RECEIVED_FILE_PATH, day, timeString);
+        snprintf(path, path_length, RECEIVED_FILE_PATH, day, timeString);
         LOGI("received file path: %s", path);
 
         FILE *fp = fopen(path, "wt");
index 5e10a8d..8332183 100644 (file)
@@ -994,6 +994,7 @@ void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestI
     }
     printf("Data: %s\n", requestInfo->info.payload);
     printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
+    printf("Resource URI: %s \n", requestInfo->info.resourceUri);
 
     if (requestInfo->info.options)
     {
@@ -1061,6 +1062,8 @@ void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *respon
     printf("Data: %s\n", responseInfo->info.payload);
     printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
     printf("Token: %s\n", responseInfo->info.token);
+    printf("Resource URI: %s \n", responseInfo->info.resourceUri);
+
     if (responseInfo->info.options)
     {
         uint32_t len = responseInfo->info.numOptions;
@@ -1203,7 +1206,13 @@ void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
                               .payloadSize = 0,
                               .resourceUri = resourceUri };
 
-    if(CA_MSG_RESET != messageType)
+    if (CA_MSG_RESET == messageType ||
+        (CA_MSG_ACKNOWLEDGE == messageType && CA_EMPTY == responseCode))
+    {
+        printf("RESET or ACK/EMPTY. there will be not payload/option\n");
+
+    }
+    else
     {
         responseData.token = (info != NULL) ? info->token : NULL;
         responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
@@ -1638,6 +1647,12 @@ bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
     // Get file length
     fseek(file, 0, SEEK_END);
     fileLen = ftell(file);
+    if (-1 == fileLen)
+    {
+        fprintf(stderr, "Failed to get file length\n");
+        fclose(file);
+        return false;
+    }
     fseek(file, 0, SEEK_SET);
 
     // Allocate memory
index 162b512..7e0810f 100644 (file)
@@ -59,6 +59,9 @@
 #define COAPS_PREFIX         "coaps://"
 #define COAPS_PREFIX_LEN     8
 
+#define COAP_TCP_PREFIX      "coap+tcp://"
+#define COAP_TCP_PREFIX_LEN  11
+
 // Iotivity Device Identity.
 const unsigned char IDENTITY[] = ("1111111111111111");
 
@@ -425,6 +428,7 @@ void send_request()
         printf("Enter the URI like below....\n");
         printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
         printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
+        printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
     }
     else
     {
@@ -808,6 +812,7 @@ void select_network()
     printf("IP     : 0\n");
     printf("GATT   : 1\n");
     printf("RFCOMM : 2\n");
+    printf("TCP    : 4\n");
     printf("select : ");
 
     char buf[MAX_BUF_LEN] = { 0 };
@@ -818,7 +823,7 @@ void select_network()
 
     int number = buf[0] - '0';
 
-    if (number < 0 || number > 3)
+    if (number < 0 || number > 4)
     {
         printf("Invalid network type\n");
         return;
@@ -844,6 +849,7 @@ void unselect_network()
     printf("IP     : 0\n");
     printf("GATT   : 1\n");
     printf("RFCOMM : 2\n");
+    printf("TCP    : 4\n");
     printf("select : ");
 
     char buf[MAX_BUF_LEN] = { 0 };
@@ -854,7 +860,7 @@ void unselect_network()
 
     int number = buf[0] - '0';
 
-    if (number < 0 || number > 3)
+    if (number < 0 || number > 4)
     {
         printf("Invalid network type\n");
         return;
@@ -1311,6 +1317,7 @@ CAResult_t get_network_type()
     printf("IP     : 0\n");
     printf("GATT   : 1\n");
     printf("RFCOMM : 2\n");
+    printf("TCP    : 4\n");
     printf("select : ");
 
     char buf[MAX_BUF_LEN] = { 0 };
@@ -1320,7 +1327,7 @@ CAResult_t get_network_type()
     }
 
     int number = buf[0] - '0';
-    if (0 > number || 2 < number)
+    if (0 > number || 4 < number)
     {
         printf("\nInvalid Network type");
         return CA_NOT_SUPPORTED;
@@ -1372,6 +1379,12 @@ void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *
         startIndex = COAP_PREFIX_LEN;
         *flags = CA_IPV4;
     }
+    else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
+    {
+        printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
+        startIndex = COAP_TCP_PREFIX_LEN;
+        *flags = CA_IPV4;
+    }
 
     // #2. copy uri for parse
     int32_t len = strlen(uri) - startIndex;
index 8c4309c..367590a 100755 (executable)
@@ -112,9 +112,6 @@ env.AppendUnique(CA_SRC = ca_common_src)
 
 if 'ALL' in ca_transport:
                transports = [ 'ip_adapter', 'bt_edr_adapter', 'bt_le_adapter']
-               if ca_os == 'linux':
-                       if with_tcp:
-                               transports.append ('tcp_adapter')
                if with_ra:
                                transports.append ('ra_adapter')
                env.SConscript(dirs = [
@@ -129,6 +126,9 @@ if 'BT' in ca_transport:
 if 'BLE' in ca_transport:
        env.SConscript(os.path.join(ca_path, 'bt_le_adapter/SConscript'))
 
+if ca_os in ['linux', 'tizen']:
+       if with_tcp == True:
+               env.SConscript(os.path.join(ca_path, 'tcp_adapter/SConscript'))
 
 print "Include path is %s" % env.get('CPPPATH')
 print "Files path is %s" % env.get('CA_SRC')
index 599423c..7d7eba2 100644 (file)
@@ -417,7 +417,7 @@ static int32_t CAReadDecryptedPayload(dtls_context_t *context,
             ((addrInfo->addr.st.ss_family == AF_INET) ? CA_IPV4 : CA_IPV6) | CA_SECURE, .port = 0 },
             .identity =
             { 0 } };
-    CAConvertAddrToName(&(addrInfo->addr.st), sep.endpoint.addr, &sep.endpoint.port);
+    CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, sep.endpoint.addr, &sep.endpoint.port);
 
     if (NULL == g_caDtlsContext)
     {
@@ -468,7 +468,7 @@ static int32_t CASendSecureData(dtls_context_t *context,
 
     CAEndpoint_t endpoint = {.adapter = CA_DEFAULT_ADAPTER};
 
-    CAConvertAddrToName(&(addrInfo->addr.st), endpoint.addr, &endpoint.port);
+    CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, endpoint.addr, &endpoint.port);
     endpoint.flags = addrInfo->addr.st.ss_family == AF_INET ? CA_IPV4 : CA_IPV6;
     endpoint.flags |= CA_SECURE;
     endpoint.adapter = CA_ADAPTER_IP;
@@ -515,7 +515,7 @@ static int32_t CAHandleSecureEvent(dtls_context_t *context,
         stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
         char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
         uint16_t port = 0;
-        CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
+        CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
         CARemovePeerFromPeerInfoList(peerAddr, port);
     }
 
@@ -553,7 +553,7 @@ static int32_t CAGetPskCredentials(dtls_context_t *ctx,
         stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
         char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
         uint16_t port = 0;
-        CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
+        CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
 
         if(CA_STATUS_OK != CAAddIdToPeerInfoList(peerAddr, port, desc, descLen) )
         {
@@ -933,7 +933,7 @@ static int CAVerifyCertificate(struct dtls_context_t *ctx, const session_t *sess
     stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
     char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
     uint16_t port = 0;
-    CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
+    CAConvertAddrToName(&(addrInfo->addr.st), addrInfo->size, peerAddr, &port);
 
     CAResult_t result = CAAddIdToPeerInfoList(peerAddr, port,
             crtChain[0].subject.data + DER_SUBJECT_HEADER_LEN + 2, crtChain[0].subject.data[DER_SUBJECT_HEADER_LEN + 1]);
index 4d8e442..3022e99 100644 (file)
@@ -122,14 +122,15 @@ CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
  * These two conversion functions return void because errors can't happen
  * (because of NI_NUMERIC), and there's nothing to do if they do happen.
  */
-void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, char *host, uint16_t *port)
+void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, socklen_t sockAddrLen,
+                         char *host, uint16_t *port)
 {
     VERIFY_NON_NULL_VOID(sockAddr, CA_ADAPTER_UTILS_TAG, "sockAddr is null");
     VERIFY_NON_NULL_VOID(host, CA_ADAPTER_UTILS_TAG, "host is null");
     VERIFY_NON_NULL_VOID(port, CA_ADAPTER_UTILS_TAG, "port is null");
 
     int r = getnameinfo((struct sockaddr *)sockAddr,
-                        sizeof (struct sockaddr_storage),
+                        sockAddrLen,
                         host, MAX_ADDR_STR_SIZE_CA,
                         NULL, 0,
                         NI_NUMERICHOST|NI_NUMERICSERV);
@@ -138,12 +139,12 @@ void CAConvertAddrToName(const struct sockaddr_storage *sockAddr, char *host, ui
         if (EAI_SYSTEM == r)
         {
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
-                            "getaddrinfo failed: errno %s", strerror(errno));
+                            "getnameinfo failed: errno %s", strerror(errno));
         }
         else
         {
             OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG,
-                            "getaddrinfo failed: %s", gai_strerror(r));
+                            "getnameinfo failed: %s", gai_strerror(r));
         }
         return;
     }
index 488686c..6fc3443 100644 (file)
@@ -1508,10 +1508,8 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     VERIFY_NON_NULL(options, TAG, "options");
 
     // get set block data from CABlock list-set.
-    coap_block_t *block1 = CAGetBlockOption(blockID,
-                                            COAP_OPTION_BLOCK1);
-    coap_block_t *block2 = CAGetBlockOption(blockID,
-                                            COAP_OPTION_BLOCK2);
+    coap_block_t *block1 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK1);
+    coap_block_t *block2 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK2);
     if (!block1 || !block2)
     {
         OIC_LOG(ERROR, TAG, "getting has failed");
@@ -1525,29 +1523,13 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
             (CA_MSG_NONCONFIRM == (*pdu)->hdr->coap_hdr_udp_t.type &&
                     CA_GET != (*pdu)->hdr->coap_hdr_udp_t.code))
     {
-        int32_t res = coap_write_block_opt(block2, COAP_OPTION_BLOCK2, *pdu, dataLength);
-        switch (res)
-        {
-            case -2: /* illegal block */
-                code = COAP_RESPONSE_CODE(CA_BAD_REQ);
-                OIC_LOG(ERROR, TAG, "write block option : -2");
-                goto error;
-            case -1: /* should really not happen */
-                OIC_LOG(ERROR, TAG, "write block option : -1");
-                break;
-            case -3: /* cannot handle request */
-                code = COAP_RESPONSE_CODE(CA_INTERNAL_SERVER_ERROR);
-                OIC_LOG(ERROR, TAG, "write block option : -3");
-                goto error;
-            default:
-                OIC_LOG(INFO, TAG, "success write block option");
-        }
+        CAGetMoreBitFromBlock(dataLength, block2);
         CALogBlockInfo(block2);
 
         // if block number is 0, add size2 option
         if (0 == block2->num)
         {
-            res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
+            CAResult_t res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "add has failed");
@@ -1556,10 +1538,18 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
             }
         }
 
+        CAResult_t res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "add has failed");
+            CARemoveBlockDataFromList(blockID);
+            return res;
+        }
+
         if (block1->num)
         {
             OIC_LOG(DEBUG, TAG, "combining block1 and block2");
-            CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+            res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
             if (CA_STATUS_OK != res)
             {
                 OIC_LOG(ERROR, TAG, "add has failed");
@@ -1570,6 +1560,14 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
             block1->num = 0;
         }
 
+        res = CAAddOptionToPDU(*pdu, options);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "add has failed");
+            CARemoveBlockDataFromList(blockID);
+            return res;
+        }
+
         if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
                             block2->num, block2->szx))
         {
@@ -1604,7 +1602,15 @@ CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     else
     {
         OIC_LOG(DEBUG, TAG, "option2, not ACK msg");
-        CAResult_t res = CAAddBlockOptionImpl(*pdu, block2, COAP_OPTION_BLOCK2, options);
+        CAResult_t res = CAAddBlockOptionImpl(block2, COAP_OPTION_BLOCK2, options);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "add has failed");
+            CARemoveBlockDataFromList(blockID);
+            return res;
+        }
+
+        res = CAAddOptionToPDU(*pdu, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
@@ -1651,7 +1657,15 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     if (CA_MSG_ACKNOWLEDGE == (*pdu)->hdr->coap_hdr_udp_t.type)
     {
         OIC_LOG(DEBUG, TAG, "option1 and ACK msg..");
-        CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+        CAResult_t res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "add has failed");
+            CARemoveBlockDataFromList(blockID);
+            return res;
+        }
+
+        res = CAAddOptionToPDU(*pdu, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
@@ -1694,13 +1708,22 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
             }
         }
 
-        res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+        res = CAAddBlockOptionImpl(block1, COAP_OPTION_BLOCK1, options);
         if (CA_STATUS_OK != res)
         {
             OIC_LOG(ERROR, TAG, "add has failed");
             CARemoveBlockDataFromList(blockID);
             return res;
         }
+
+        res = CAAddOptionToPDU(*pdu, options);
+        if (CA_STATUS_OK != res)
+        {
+            OIC_LOG(ERROR, TAG, "add has failed");
+            CARemoveBlockDataFromList(blockID);
+            return res;
+        }
+
         CALogBlockInfo(block1);
 
         if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
@@ -1740,11 +1763,10 @@ CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t data
     return CA_STATUS_OK;
 }
 
-CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType,
+CAResult_t CAAddBlockOptionImpl(coap_block_t *block, uint8_t blockType,
                                 coap_list_t **options)
 {
     OIC_LOG(DEBUG, TAG, "IN-AddBlockOptionImpl");
-    VERIFY_NON_NULL(pdu, TAG, "pdu");
     VERIFY_NON_NULL(block, TAG, "block");
     VERIFY_NON_NULL(options, TAG, "options");
 
@@ -1762,6 +1784,12 @@ CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t bl
         return CA_STATUS_INVALID_PARAM;
     }
 
+    OIC_LOG(DEBUG, TAG, "OUT-AddBlockOptionImpl");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAAddOptionToPDU(coap_pdu_t *pdu, coap_list_t **options)
+{
     // after adding the block option to option list, add option list to pdu.
     if (*options)
     {
@@ -1771,15 +1799,18 @@ CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t bl
                       COAP_OPTION_DATA(*(coap_option *) opt->data));
 
             OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
-            coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
-                            COAP_OPTION_LENGTH(*(coap_option *) opt->data),
-                            COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+            int ret = coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+                                      COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+                                      COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+            if (!ret)
+            {
+                return CA_STATUS_FAILED;
+            }
         }
     }
 
     OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
 
-    OIC_LOG(DEBUG, TAG, "OUT-AddBlockOptionImpl");
     return CA_STATUS_OK;
 }
 
index 9f6aef8..a71b849 100644 (file)
@@ -63,6 +63,11 @@ CAResult_t CAInitialize()
 
     if (!g_isInitialized)
     {
+        if (0 != OCSeedRandom())
+        {
+            OIC_LOG(ERROR, TAG, "Seed Random Failed");
+        }
+
         CAResult_t res = CAInitializeMessageHandler();
         if (res != CA_STATUS_OK)
         {
@@ -71,6 +76,7 @@ CAResult_t CAInitialize()
         }
         g_isInitialized = true;
     }
+
     return CA_STATUS_OK;
 }
 
index fd0be7e..e007d87 100644 (file)
@@ -1275,7 +1275,7 @@ static void CALogPayloadInfo(CAInfo_t *info)
         {
             for (uint32_t i = 0; i < info->numOptions; i++)
             {
-                OIC_LOG_V(DEBUG, TAG, "optionID: %d", info->options[i].optionID);
+                OIC_LOG_V(DEBUG, TAG, "optionID: %u", info->options[i].optionID);
 
                 OIC_LOG_V(DEBUG, TAG, "list: %s", info->options[i].optionData);
             }
@@ -1293,7 +1293,7 @@ static void CALogPayloadInfo(CAInfo_t *info)
             OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *) info->token,
                            info->tokenLength);
         }
-        OIC_LOG_V(DEBUG, TAG, "msgID: %d", info->messageId);
+        OIC_LOG_V(DEBUG, TAG, "msgID: %u", info->messageId);
     }
     else
     {
index 227543d..0cb8a18 100644 (file)
@@ -24,7 +24,6 @@
 // For glibc information on feature test macros,
 // Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
 //
-// This file requires #define use due to random() and srandom()
 // For details on compatibility and glibc support,
 // Refer http://www.gnu.org/software/libc/manual/html_node/BSD-Random.html
 #define _DEFAULT_SOURCE
 #include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-
-// ARM GCC compiler doesnt define srandom function.
-#if defined(ARDUINO) && !defined(ARDUINO_ARCH_SAM)
-#define HAVE_SRANDOM 1
-#endif
+#include "ocrandom.h"
 
 #define TAG "CA_PRTCL_MSG"
 
@@ -65,8 +60,6 @@
 
 static const char COAP_URI_HEADER[] = "coap://[::]/";
 
-static unsigned int SEED = 0;
-
 CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
                                    CARequestInfo_t *outReqInfo)
 {
@@ -127,6 +120,13 @@ coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_
     // and ACKNOWLEDGE can use empty message when code is empty.
     if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
     {
+        if ((CA_EMPTY == code) && (info->payloadSize > 0 || info->payload
+            || info->token || info->tokenLength > 0))
+        {
+            OIC_LOG(ERROR, TAG, "Empty message has unnecessary data after messageID");
+            return NULL;
+        }
+
         OIC_LOG(DEBUG, TAG, "code is empty");
         if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL, transport)))
         {
@@ -136,7 +136,7 @@ coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_
     }
     else
     {
-        if (CA_MSG_ACKNOWLEDGE != info->type && info->resourceUri)
+        if (info->resourceUri)
         {
             uint32_t length = strlen(info->resourceUri);
             if (CA_MAX_URI_LENGTH < length)
@@ -1035,26 +1035,6 @@ CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
         return CA_STATUS_INVALID_PARAM;
     }
 
-    if (SEED == 0)
-    {
-#ifdef ARDUINO
-        SEED = now();
-#else
-        SEED = time(NULL);
-#endif
-        if (SEED == (unsigned int)((time_t)-1))
-        {
-            OIC_LOG(ERROR, TAG, "seed is not made");
-            SEED = 0;
-            return CA_STATUS_FAILED;
-        }
-#if HAVE_SRANDOM
-        srandom(SEED);
-#else
-        srand(SEED);
-#endif
-    }
-
     // memory allocation
     char *temp = (char *) OICCalloc(tokenLength, sizeof(char));
     if (NULL == temp)
@@ -1063,16 +1043,7 @@ CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    // set random byte
-    for (uint8_t index = 0; index < tokenLength; index++)
-    {
-        // use valid characters
-#ifdef ARDUINO
-        temp[index] = rand() & 0x00FF;
-#else
-        temp[index] = random() & 0x00FF;
-#endif
-    }
+    OCFillRandomMem((uint8_t *)temp, tokenLength);
 
     // save token
     *token = temp;
index 5dd5b87..08c46b0 100644 (file)
@@ -120,7 +120,6 @@ static void CAReceiveHandler(void *data)
 {
     (void)data;
     OIC_LOG(DEBUG, TAG, "IN");
-
     while (!caglobals.ip.terminate)
     {
         CAFindReadyMessage();
@@ -196,8 +195,10 @@ static void CASelectReturned(fd_set *readFds, int ret)
             CAHandleNetlink();
             break;
         }
-        else
+        else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
         {
+            char buf[10];
+            (void)read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
             CAInterface_t *ifchanged = CAFindInterfaceChange();
             if (ifchanged)
             {
@@ -206,6 +207,10 @@ static void CASelectReturned(fd_set *readFds, int ret)
             }
             break;
         }
+        else
+        {
+            break;
+        }
 
         (void)CAReceiveMessage(fd, flags);
         FD_CLR(fd, readFds);
@@ -299,7 +304,7 @@ static CAResult_t CAReceiveMessage(int fd, CATransportFlags_t flags)
         }
     }
 
-    CAConvertAddrToName(&srcAddr, sep.endpoint.addr, &sep.endpoint.port);
+    CAConvertAddrToName(&srcAddr, msg.msg_namelen, sep.endpoint.addr, &sep.endpoint.port);
 
     if (flags & CA_SECURE)
     {
index 5e55c1f..d2dcf44 100644 (file)
@@ -15,7 +15,7 @@ src_dir = './tcp_adapter/'
 
 # Source files to build common for all platforms
 common_files = None
-if target_os == 'linux':
+if target_os in ['linux', 'tizen']:
     common_files = [
         os.path.join(src_dir, 'catcpadapter.c'),
         os.path.join(src_dir, 'catcpserver.c') ]
index 2054a01..b0fca46 100644 (file)
@@ -478,7 +478,7 @@ static void CAAcceptHandler(void *data)
                 }
                 svritem->u4tcp.fd = sockfd;
 
-                CAConvertAddrToName((struct sockaddr_storage *)&clientaddr,
+                CAConvertAddrToName((struct sockaddr_storage *)&clientaddr, clientlen,
                                     (char *) &svritem->addr, &svritem->u4tcp.port);
 
                 ca_mutex_lock(g_mutexObjectList);
index a95101f..5b6b38b 100644 (file)
@@ -662,7 +662,7 @@ WARN_LOGFILE           =
 INPUT                  = . \
                                                 ../stack/include \
                                                 ../ocsocket/include \
-                                                ../ocrandom/include \
+                                                ../../c_common/ocrandom/include \
                                                 ../occoap/include \
 
 # This tag can be used to specify the character encoding of the source files
index d3d68ba..1d2a067 100644 (file)
@@ -18,7 +18,7 @@ if env.get('ROUTING') == 'GW':
                                os.path.join(Dir('.').abspath, './../stack/include/internal'),
                                os.path.join(Dir('.').abspath, './../logger'),
                                os.path.join(Dir('.').abspath, './../../oc_logger/include'),
-                               os.path.join(Dir('.').abspath, './../ocrandom/include'),
+                               os.path.join(Dir('.').abspath, './../../c_common/ocrandom/include'),
                                os.path.join(Dir('.').abspath, './../connectivity/api'),
                                os.path.join(Dir('.').abspath, './../connectivity/common/inc'),
                                os.path.join(Dir('.').abspath, './../security/include'),
index d9d76f7..b611490 100644 (file)
@@ -609,7 +609,7 @@ bool RTMIsObserverPresent(CAEndpoint_t devAddr, OCObservationId *obsID,
     while (NULL != iterTable)
     {
         RTMGatewayEntry_t *entry = u_linklist_get_data(iterTable);
-        if (NULL == entry && NULL == entry->destination)
+        if (NULL == entry || NULL == entry->destination)
         {
             OC_LOG(ERROR, TAG, "entry is NULL");
             return false;
index 7f342a7..a0925c2 100644 (file)
@@ -203,7 +203,7 @@ void RMGetRouteOptionIndex(const CAHeaderOption_t *options, uint8_t numOptions,
     RM_NULL_CHECK_VOID(index, TAG, "index");
     for (uint32_t i = 0; i < numOptions; i++)
     {
-        OC_LOG_V(DEBUG, TAG, "Request- optionID: %d", options[i].optionID);
+        OC_LOG_V(DEBUG, TAG, "Request- optionID: %u", options[i].optionID);
         if (RM_OPTION_MESSAGE_SWITCHING == options[i].optionID)
         {
             OC_LOG_V(INFO, TAG, "Found Option at %d", i);
index 6d83044..4dcb4c2 100755 (executable)
@@ -42,7 +42,7 @@ libocsrm_env.PrependUnique(CPPPATH = [
                '../../../extlibs/cjson/',
                '../../../extlibs/tinydtls/',
                '../logger/include',
-               '../ocrandom/include',
+               '../../c_common/ocrandom/include',
                '../stack/include',
                '../stack/include/internal',
                '../../oc_logger/include',
index ae092df..74ea373 100644 (file)
@@ -110,6 +110,15 @@ OCStackResult AddCredential(OicSecCred_t * cred);
  */
 OCStackResult RemoveCredential(const OicUuid_t* credId);
 
+/**
+ * Remove all credential data on credential resource and persistent storage
+ *
+ * @retval
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_ERROR           - stack process error
+ */
+OCStackResult RemoveAllCredentials(void);
+
 #if defined(__WITH_DTLS__)
 /**
  * This internal callback is used by lower stack (i.e. CA layer) to
index 65d7855..06cd5bb 100644 (file)
@@ -30,7 +30,7 @@ root_dir = './../../../../'
 provisioning_env.AppendUnique(CPPPATH = [
                '../../stack/include',
                '../../stack/include/internal',
-               '../../ocrandom/include',
+               '../../../c_common/ocrandom/include',
                '../../logger/include',
                '../../../oc_logger/include',
                '../../ocmalloc/include',
index f1d251c..b368fe3 100644 (file)
@@ -28,7 +28,7 @@ provisioning_env = env.Clone()
 ######################################################################
 provisioning_env.AppendUnique(CPPPATH = [
                '../../../../stack/include',
-               '../../../../ocrandom/include',
+               '../../../../../c_common/ocrandom/include',
                '../../../../logger/include',
                '../../../../security/include',
                '../../../../../oc_logger/include',
old mode 100644 (file)
new mode 100755 (executable)
index f6e2ff3..60daa64
@@ -343,7 +343,7 @@ bool PMGenerateQuery(bool isSecure,
     switch(connType & CT_MASK_ADAPTER)
     {
         case CT_ADAPTER_IP:
-            switch(connType & CT_MASK_FLAGS)
+            switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
             {
                 case CT_IP_USE_V4:
                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
@@ -534,13 +534,20 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                     DeleteDoxmBinData(ptrDoxm);
                     return OC_STACK_KEEP_TRANSACTION;
                 }
-
+                char rsrc_uri[MAX_URI_LENGTH+1] = {0};
+                int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
+                          OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
+                if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
+                {
+                    OC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
+                    return OC_STACK_ERROR;
+                }
                 //Try to the unicast discovery to getting secure port
-                char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
+                char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
                 if(!PMGenerateQuery(false,
                                     clientResponse->devAddr.addr, clientResponse->devAddr.port,
                                     clientResponse->connType,
-                                    query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
+                                    query, sizeof(query), rsrc_uri))
                 {
                     OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
                     return OC_STACK_KEEP_TRANSACTION;
index c0f7377..7e4e301 100644 (file)
@@ -200,7 +200,9 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
 
     //Verifying if the ID of the sender is an AMS service that this device trusts.
     if(resPayload &&
-       memcmp(context->amsMgrContext->amsDeviceId.id, resPayload->sid,
+       memcmp(context->amsMgrContext->amsDeviceId.id,
+            ((OCDiscoveryPayload*)clientResponse->payload)->sid,
+            // resPayload->sid,
                     sizeof(context->amsMgrContext->amsDeviceId.id)) != 0)
     {
         context->retVal = ACCESS_DENIED_AMS_SERVICE_ERROR;
index e7235b5..660164b 100644 (file)
@@ -570,6 +570,14 @@ exit:
     return 0;
 }
 
+/**
+ * Get the default value
+ * @retval  NULL for now. Update it when we finalize the default info.
+ */
+static OicSecCred_t* GetCredDefault()
+{
+    return NULL;
+}
 
 /**
  * This function adds the new cred to the credential list.
@@ -631,6 +639,25 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
 
 }
 
+/**
+ * Remove all credential data on credential resource and persistent storage
+ *
+ * @retval
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_ERROR           - stack process error
+ */
+OCStackResult RemoveAllCredentials(void)
+{
+    DeleteCredList(gCred);
+    gCred = GetCredDefault();
+
+    if(!UpdatePersistentStorage(gCred))
+    {
+        return OC_STACK_ERROR;
+    }
+    return OC_STACK_OK;
+}
+
 static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
@@ -758,15 +785,6 @@ OCStackResult CreateCredResource()
 }
 
 /**
- * Get the default value
- * @retval  NULL for now. Update it when we finalize the default info.
- */
-static OicSecCred_t* GetCredDefault()
-{
-    return NULL;
-}
-
-/**
  * Initialize Cred resource by loading data from persistent storage.
  *
  * @retval
old mode 100755 (executable)
new mode 100644 (file)
index d453621..57e077a
@@ -60,6 +60,43 @@ bool OCRepPayloadGetPropInt(const OCRepPayload* payload, const char* name, int64
 bool OCRepPayloadSetPropDouble(OCRepPayload* payload, const char* name, double value);
 bool OCRepPayloadGetPropDouble(const OCRepPayload* payload, const char* name, double* value);
 
+/**
+ * This function allocates memory for the byte string and sets it in the payload.
+ *
+ * @param payload      Pointer to the payload to which byte string needs to be added.
+ * @param name         Name of the byte string.
+ * @param value        Byte string and it's length.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value);
+
+/**
+ * This function sets the byte string in the payload.
+ *
+ * @param payload      Pointer to the payload to which byte string needs to be added.
+ * @param name         Name of the byte string.
+ * @param value        Byte string and it's length.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name,
+        OCByteString* value);
+
+/**
+ * This function gets the byte string from the payload.
+ *
+ * @param payload      Pointer to the payload from which byte string needs to be retrieved.
+ * @param name         Name of the byte string.
+ * @param value        Byte string and it's length.
+ *
+ * @note: Caller needs to invoke OCFree on value.bytes after it is finished using the byte string.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name,
+        OCByteString* value);
+
 bool OCRepPayloadSetPropString(OCRepPayload* payload, const char* name, const char* value);
 bool OCRepPayloadSetPropStringAsOwner(OCRepPayload* payload, const char* name, char* value);
 bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, char** value);
@@ -72,6 +109,48 @@ bool OCRepPayloadSetPropObjectAsOwner(OCRepPayload* payload, const char* name,
         OCRepPayload* value);
 bool OCRepPayloadGetPropObject(const OCRepPayload* payload, const char* name, OCRepPayload** value);
 
+/**
+ * This function allocates memory for the byte string array and sets it in the payload.
+ *
+ * @param payload      Pointer to the payload to which byte string array needs to be added.
+ * @param name         Name of the byte string.
+ * @param array        Byte string array.
+ * @param dimensions   Number of byte strings in above array.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+        OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+/**
+ * This function sets the byte string array in the payload.
+ *
+ * @param payload      Pointer to the payload to which byte string array needs to be added.
+ * @param name         Name of the byte string.
+ * @param array        Byte string array.
+ * @param dimensions   Number of byte strings in above array.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+        const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
+/**
+ * This function gets the byte string array from the payload.
+ *
+ * @param payload      Pointer to the payload from which byte string array needs to be retrieved.
+ * @param name         Name of the byte string array.
+ * @param value        Byte string array.
+ * @param dimensions   Number of byte strings in above array.
+ *
+ * @note: Caller needs to invoke OICFree on 'bytes' field of all array elements after it is
+ *        finished using the byte string array.
+ *
+ * @return true on success, false upon failure.
+ */
+bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+        OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
+
 bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
         int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH]);
 bool OCRepPayloadSetIntArray(OCRepPayload* payload, const char* name,
@@ -127,13 +206,13 @@ OCResourcePayload* OCDiscoveryPayloadGetResource(OCDiscoveryPayload* payload, si
 void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload);
 
 // Device Payload
-OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, const char* dname,
+OCDevicePayload* OCDevicePayloadCreate(const uint8_t* sid, const char* dname,
         const char* specVer, const char* dmVer);
 void OCDevicePayloadDestroy(OCDevicePayload* payload);
 
 // Platform Payload
-OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo* platformInfo);
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* platformInfo);
+OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo);
+OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo);
 
 void OCPlatformPayloadDestroy(OCPlatformPayload* payload);
 
index 9e67e78..4125f4d 100644 (file)
@@ -137,6 +137,12 @@ extern "C" {
 /** To represent resource type with presence.*/
 #define OC_RSRVD_RESOURCE_TYPE_PRESENCE "oic.wk.ad"
 
+/** To represent resource type with device.*/
+#define OC_RSRVD_RESOURCE_TYPE_DEVICE   "oic.wk.d"
+
+/** To represent resource type with platform.*/
+#define OC_RSRVD_RESOURCE_TYPE_PLATFORM "oic.wk.p"
+
 /** To represent interface.*/
 #define OC_RSRVD_INTERFACE              "if"
 
@@ -155,6 +161,9 @@ extern "C" {
 /** To represent default interface.*/
 #define OC_RSRVD_INTERFACE_DEFAULT      "oic.if.baseline"
 
+/** To represent read-only interface.*/
+#define OC_RSRVD_INTERFACE_READ         "oic.if.r"
+
 /** To represent ll interface.*/
 #define OC_RSRVD_INTERFACE_LL           "oic.if.ll"
 
@@ -245,10 +254,10 @@ extern "C" {
 #define OC_RSRVD_DATA_MODEL_VERSION     "dmv"
 
 /** Device specification version.*/
-#define OC_SPEC_VERSION                "0.9.0"
+#define OC_SPEC_VERSION                "core.1.0.0"
 
 /** Device Data Model version.*/
-#define OC_DATA_MODEL_VERSION          "sec.0.95"
+#define OC_DATA_MODEL_VERSION          "res.1.0.0"
 
 /**
  *  These provide backward compatibility - their use is deprecated.
@@ -336,11 +345,8 @@ typedef enum
     /**Remote Access over XMPP.*/
     OC_ADAPTER_REMOTE_ACCESS = (1 << 3),
 #endif
-
-#ifdef TCP_ADAPTER
     /** CoAP over TCP.*/
     OC_ADAPTER_TCP           = (1 << 4)
-#endif
 
 } OCTransportAdapter;
 
@@ -462,11 +468,8 @@ typedef enum
     /** Remote Access over XMPP.*/
     CT_ADAPTER_REMOTE_ACCESS = (1 << 19),
 #endif
-
-#ifdef TCP_ADAPTER
     /** CoAP over TCP.*/
     CT_ADAPTER_TCP          = (1 << 20),
-#endif
 
     /** Insecure transport is the default (subject to change).*/
 
@@ -937,10 +940,21 @@ typedef enum
     OCREP_PROP_DOUBLE,
     OCREP_PROP_BOOL,
     OCREP_PROP_STRING,
+    OCREP_PROP_BYTE_STRING,
     OCREP_PROP_OBJECT,
     OCREP_PROP_ARRAY
 }OCRepPayloadPropType;
 
+/** This structure will be used to represent a binary string for CBOR payloads.*/
+typedef struct
+{
+    /** pointer to data bytes.*/
+    uint8_t* bytes;
+
+    /** number of data bytes.*/
+    size_t   len;
+} OCByteString;
+
 #define MAX_REP_ARRAY_DEPTH 3
 typedef struct
 {
@@ -953,6 +967,10 @@ typedef struct
         double* dArray;
         bool* bArray;
         char** strArray;
+
+        /** pointer to ByteString array.*/
+        OCByteString* ocByteStrArray;
+
         struct OCRepPayload** objArray;
     };
 } OCRepPayloadValueArray;
@@ -967,6 +985,10 @@ typedef struct OCRepPayloadValue
         double d;
         bool b;
         char* str;
+
+        /** ByteString object.*/
+        OCByteString ocByteStr;
+
         struct OCRepPayload* obj;
         OCRepPayloadValueArray arr;
     };
@@ -995,7 +1017,6 @@ typedef struct OCRepPayload
 typedef struct OCResourcePayload
 {
     char* uri;
-    uint8_t* sid;
     OCStringLL* types;
     OCStringLL* interfaces;
     uint8_t bitmap;
@@ -1089,6 +1110,9 @@ typedef struct OCResourceCollectionPayload
 typedef struct
 {
     OCPayload base;
+
+    uint8_t* sid;
+
     /** This structure holds the old /oic/res response. */
     OCResourcePayload *resources;
     /** This structure holds the collection response for the /oic/res. */
@@ -1123,7 +1147,6 @@ typedef struct
 typedef struct
 {
     OCPayload base;
-    char* uri;
     uint8_t* sid;
     char* deviceName;
     char* specVersion;
index 1269779..4c4dfbb 100644 (file)
@@ -158,15 +158,14 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
         OC_LOG(level, PL_TAG, "\tNO Resources");
         return;
     }
-
+    OC_LOG(level, PL_TAG, "\tSID:");
+    OC_LOG_BUFFER(level, PL_TAG, payload->sid, UUID_SIZE);
     OCResourcePayload* res = payload->resources;
 
     while(res)
     {
         OC_LOG_V(level, PL_TAG, "\tResource #%d", i);
         OC_LOG_V(level, PL_TAG, "\tURI:%s", res->uri);
-        OC_LOG(level, PL_TAG, "\tSID:");
-        OC_LOG_BUFFER(level, PL_TAG, res->sid, UUID_SIZE);
         OC_LOG(level, PL_TAG, "\tResource Types:");
         OCStringLL* strll =  res->types;
         while(strll)
@@ -194,7 +193,6 @@ static inline void OCPayloadLogDiscovery(LogLevel level, OCDiscoveryPayload* pay
 static inline void OCPayloadLogDevice(LogLevel level, OCDevicePayload* payload)
 {
     OC_LOG(level, PL_TAG, "Payload Type: Device");
-    OC_LOG_V(level, PL_TAG, "\tURI:%s", payload->uri);
     OC_LOG(level, PL_TAG, "\tSID:");
     OC_LOG_BUFFER(level, PL_TAG, payload->sid, UUID_SIZE);
     OC_LOG_V(level, PL_TAG, "\tDevice Name:%s", payload->deviceName);
index d396db1..419593a 100644 (file)
@@ -393,17 +393,23 @@ void queryResource()
 
 void collectUniqueResource(const OCClientResponse * clientResponse)
 {
-    OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+    OCDiscoveryPayload* pay = (OCDiscoveryPayload*) clientResponse->payload;
+    OCResourcePayload* res = pay->resources;
+
+    // Including the NUL terminator, length of UUID string of the form:
+    //   "a62389f7-afde-00b6-cd3e-12b97d2fcf09"
+#   define UUID_LENGTH 37
+
     char sidStr[UUID_LENGTH];
 
     while(res) {
 
         int ret = snprintf(sidStr, UUID_LENGTH,
                 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
-                res->sid[0], res->sid[1], res->sid[2], res->sid[3],
-                res->sid[4], res->sid[5], res->sid[6], res->sid[7],
-                res->sid[8], res->sid[9], res->sid[10], res->sid[11],
-                res->sid[12], res->sid[13], res->sid[14], res->sid[15]
+                pay->sid[0], pay->sid[1], pay->sid[2], pay->sid[3],
+                pay->sid[4], pay->sid[5], pay->sid[6], pay->sid[7],
+                pay->sid[8], pay->sid[9], pay->sid[10], pay->sid[11],
+                pay->sid[12], pay->sid[13], pay->sid[14], pay->sid[15]
                 );
 
         if (ret == UUID_LENGTH - 1)
index cf7d754..485eda3 100755 (executable)
@@ -197,6 +197,10 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
     {
         OICFree(val->str);
     }
+    else if(val->type == OCREP_PROP_BYTE_STRING)
+    {
+        OICFree(val->ocByteStr.bytes);
+    }
     else if (val->type == OCREP_PROP_OBJECT)
     {
         OCRepPayloadDestroy(val->obj);
@@ -220,6 +224,13 @@ static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val)
                 }
                 OICFree(val->arr.strArray);
                 break;
+            case OCREP_PROP_BYTE_STRING:
+                for (size_t i = 0; i< dimTotal; ++i)
+                {
+                    OICFree(val->arr.ocByteStrArray[i].bytes);
+                }
+                OICFree(val->arr.ocByteStrArray);
+                break;
             case OCREP_PROP_OBJECT:
                 for(size_t i = 0; i< dimTotal;++i)
                 {
@@ -479,6 +490,9 @@ static bool OCRepPayloadSetProp(OCRepPayload* payload, const char* name,
         case OCREP_PROP_STRING:
                val->str = (char*)value;
                return val->str != NULL;
+        case OCREP_PROP_BYTE_STRING:
+               val->ocByteStr = *(OCByteString*)value;
+               break;
         case OCREP_PROP_NULL:
                return val != NULL;
         case OCREP_PROP_ARRAY:
@@ -562,6 +576,62 @@ bool OCRepPayloadGetPropString(const OCRepPayload* payload, const char* name, ch
     return *value != NULL;
 }
 
+bool OCRepPayloadSetPropByteString(OCRepPayload* payload, const char* name, OCByteString value)
+{
+    if (!value.bytes || !value.len)
+    {
+        return false;
+    }
+
+    OCByteString ocByteStr = {
+                    .bytes = (uint8_t*)OICMalloc(value.len * sizeof(uint8_t)),
+                    .len = value.len };
+
+    if(!ocByteStr.bytes)
+    {
+        return false;
+    }
+    memcpy(ocByteStr.bytes, value.bytes, ocByteStr.len);
+
+    bool b = OCRepPayloadSetPropByteStringAsOwner(payload, name, &ocByteStr);
+
+    if(!b)
+    {
+        OICFree(ocByteStr.bytes);
+    }
+    return b;
+}
+
+bool OCRepPayloadSetPropByteStringAsOwner(OCRepPayload* payload, const char* name, OCByteString* value)
+{
+    return OCRepPayloadSetProp(payload, name, value, OCREP_PROP_BYTE_STRING);
+}
+
+bool OCRepPayloadGetPropByteString(const OCRepPayload* payload, const char* name, OCByteString* value)
+{
+    OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+    if (!val || val->type != OCREP_PROP_BYTE_STRING)
+    {
+        return false;
+    }
+
+    if (!value)
+    {
+        return false;
+    }
+
+    value->bytes = (uint8_t*)OICMalloc(val->ocByteStr.len * sizeof(uint8_t));
+    if (!value->bytes)
+    {
+        return false;
+    }
+    value->len = val->ocByteStr.len;
+    memcpy(value->bytes, val->ocByteStr.bytes, value->len);
+
+    return true;
+}
+
 bool OCRepPayloadSetPropBool(OCRepPayload* payload,
         const char* name, bool value)
 {
@@ -626,6 +696,123 @@ size_t calcDimTotal(const size_t dimensions[MAX_REP_ARRAY_DEPTH])
     return total;
 }
 
+
+bool OCRepPayloadSetByteStringArrayAsOwner(OCRepPayload* payload, const char* name,
+        OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+    OCRepPayloadValue* val = OCRepPayloadFindAndSetValue(payload, name, OCREP_PROP_ARRAY);
+
+    if (!val)
+    {
+        return false;
+    }
+
+    val->arr.type = OCREP_PROP_BYTE_STRING;
+    memcpy(val->arr.dimensions, dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+    val->arr.ocByteStrArray = array;
+
+    return true;
+}
+
+bool OCRepPayloadSetByteStringArray(OCRepPayload* payload, const char* name,
+        const OCByteString* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+    if (!array)
+    {
+        return NULL;
+    }
+
+    size_t dimTotal = calcDimTotal(dimensions);
+    if (dimTotal == 0)
+    {
+        return false;
+    }
+
+    OCByteString* newArray = (OCByteString*)OICCalloc(dimTotal, sizeof(OCByteString));
+
+    if (!newArray)
+    {
+        return false;
+    }
+
+    for (size_t i = 0; i < dimTotal; ++i)
+    {
+        newArray[i].bytes = (uint8_t*)OICMalloc(array[i].len * sizeof(uint8_t));
+        if (NULL == newArray[i].bytes)
+        {
+            for (size_t j = 0; j < i; ++j)
+            {
+                OICFree(newArray[j].bytes);
+            }
+
+            OICFree(newArray);
+            return false;
+        }
+        newArray[i].len = array[i].len;
+        memcpy(newArray[i].bytes, array[i].bytes, newArray[i].len);
+    }
+
+    bool b = OCRepPayloadSetByteStringArrayAsOwner(payload, name, newArray, dimensions);
+    if (!b)
+    {
+        for (size_t i = 0; i < dimTotal; ++i)
+        {
+            OICFree(newArray[i].bytes);
+        }
+
+        OICFree(newArray);
+    }
+    return b;
+}
+
+bool OCRepPayloadGetByteStringArray(const OCRepPayload* payload, const char* name,
+        OCByteString** array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
+{
+    OCRepPayloadValue* val = OCRepPayloadFindValue(payload, name);
+
+    if (!val || val->type != OCREP_PROP_ARRAY || val->arr.type != OCREP_PROP_BYTE_STRING
+            || !val->arr.ocByteStrArray)
+    {
+        return false;
+    }
+
+    size_t dimTotal = calcDimTotal(val->arr.dimensions);
+    if (dimTotal == 0)
+    {
+        return false;
+    }
+
+    *array = (OCByteString*)OICCalloc(dimTotal, sizeof(OCByteString));
+    if (!*array)
+    {
+        return false;
+    }
+
+    for (size_t i = 0; i < dimTotal; ++i)
+    {
+        OCByteString* tmp = &(*array)[i];
+        tmp->bytes = (uint8_t*)OICMalloc(val->arr.ocByteStrArray[i].len * sizeof(uint8_t));
+        if (NULL == tmp->bytes)
+        {
+            for (size_t j = 0; j < i; ++j)
+            {
+                OCByteString* tmp = &(*array)[j];
+                OICFree(tmp->bytes);
+            }
+            OICFree(*array);
+            *array = NULL;
+
+            return false;
+        }
+        tmp->len = val->arr.ocByteStrArray[i].len;
+        memcpy(tmp->bytes, val->arr.ocByteStrArray[i].bytes, tmp->len);
+    }
+
+    memcpy(dimensions, val->arr.dimensions, MAX_REP_ARRAY_DEPTH * sizeof(size_t));
+    return true;
+}
+
+
 bool OCRepPayloadSetIntArrayAsOwner(OCRepPayload* payload, const char* name,
         int64_t* array, size_t dimensions[MAX_REP_ARRAY_DEPTH])
 {
@@ -1166,13 +1353,12 @@ static OCResourcePayload* OCCopyResource(const OCResource* res, uint16_t port)
     }
 
     pl->uri = OICStrdup(res->uri);
-    pl->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
-    if(!pl->uri || ! pl->sid)
+
+    if(!pl->uri)
     {
         FreeOCDiscoveryResource(pl);
         return NULL;
     }
-    memcpy(pl->sid, OCGetServerInstanceID(), UUID_SIZE);
 
     // types
     OCResourceType* typePtr = res->rsrcType;
@@ -1387,7 +1573,6 @@ static void FreeOCDiscoveryResource(OCResourcePayload* payload)
     }
 
     OICFree(payload->uri);
-    OICFree(payload->sid);
     OCFreeOCStringLL(payload->types);
     OCFreeOCStringLL(payload->interfaces);
     FreeOCDiscoveryResource(payload->next);
@@ -1400,12 +1585,12 @@ void OCDiscoveryPayloadDestroy(OCDiscoveryPayload* payload)
     {
         return;
     }
-
+    OICFree(payload->sid);
     FreeOCDiscoveryResource(payload->resources);
     OICFree(payload);
 }
 
-OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, const char* dname,
+OCDevicePayload* OCDevicePayloadCreate(const uint8_t* sid, const char* dname,
         const char* specVer, const char* dmVer)
 {
 
@@ -1418,12 +1603,6 @@ OCDevicePayload* OCDevicePayloadCreate(const char* uri, const uint8_t* sid, cons
 
     payload->base.type = PAYLOAD_TYPE_DEVICE;
 
-    payload->uri = OICStrdup(uri);
-    if(uri && !payload->uri)
-    {
-        goto exit;
-    }
-
     if(sid)
     {
         payload->sid = (uint8_t*)OICMalloc(UUID_SIZE);
@@ -1466,7 +1645,6 @@ void OCDevicePayloadDestroy(OCDevicePayload* payload)
         return;
     }
 
-    OICFree(payload->uri);
     OICFree(payload->sid);
     OICFree(payload->deviceName);
     OICFree(payload->specVersion);
@@ -1494,7 +1672,7 @@ static void OCCopyPlatformInfo(const OCPlatformInfo* platformInfo, OCPlatformPay
     target->info.systemTime = OICStrdup(platformInfo->systemTime);
 }
 
-OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* platformInfo)
+OCPlatformPayload* OCPlatformPayloadCreateAsOwner(OCPlatformInfo* platformInfo)
 {
     OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
     if(!payload)
@@ -1503,13 +1681,12 @@ OCPlatformPayload* OCPlatformPayloadCreateAsOwner(char* uri, OCPlatformInfo* pla
     }
 
     payload->base.type = PAYLOAD_TYPE_PLATFORM;
-    payload->uri = uri;
     payload->info = *platformInfo;
 
     return payload;
 }
 
-OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo* platformInfo)
+OCPlatformPayload* OCPlatformPayloadCreate(const OCPlatformInfo* platformInfo)
 {
     OCPlatformPayload* payload = (OCPlatformPayload*)OICCalloc(1, sizeof(OCPlatformPayload));
 
@@ -1519,7 +1696,6 @@ OCPlatformPayload* OCPlatformPayloadCreate(const char* uri, const OCPlatformInfo
     }
 
     payload->base.type = PAYLOAD_TYPE_PLATFORM;
-    payload->uri = OICStrdup(uri);
     OCCopyPlatformInfo(platformInfo, payload);
 
     return payload;
index 588dd55..7b46b36 100644 (file)
@@ -50,6 +50,7 @@ static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayl
 static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* outPayload,
         size_t* size);
 static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, size_t* size);
+static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload* payload);
 static int64_t OCConvertPresencePayload(OCPresencePayload* payload, uint8_t* outPayload,
         size_t* size);
 static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
@@ -183,22 +184,17 @@ static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* out
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
 
-    CborEncoder rootArray;
-    err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
     CborEncoder map;
 
-    err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+    err = err | cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
 
     if(payload->securityData)
     {
-        err = err | AddTextStringToMap(&map, OC_RSRVD_REPRESENTATION,
-                sizeof(OC_RSRVD_REPRESENTATION) - 1,
-                payload->securityData);
+        err = err | cbor_encode_text_string(&map, payload->securityData,
+                                            strlen(payload->securityData));
     }
 
-    err = err | cbor_encoder_close_container(&rootArray, &map);
-
-    err = err | cbor_encoder_close_container(&encoder, &rootArray);
+    err = err | cbor_encoder_close_container(&encoder, &map);
     return checkError(err, &encoder, outPayload, size);
 
 }
@@ -287,12 +283,50 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* o
     }
     else if (payload->resources)
     {
+        /*
+        The format for the payload is "modelled" as JSON.
+
+        [                                                       // rootArray
+            {                                                   // rootMap
+                "di" : UUID,                                    // device ID
+                links :[                                        // linksArray contains maps of resources
+                            {
+                                href, rt, if, policy            // Resource 1
+                            },
+                            {
+                                href, rt, if, policy            // Resource 2
+                            },
+                            .
+                            .
+                            .
+                        ]
+            }
+        ]
+        */
+        CborEncoder rootMap = {};
         size_t resourceCount =  OCDiscoveryPayloadGetResourceCount(payload);
-        err = err | cbor_encoder_create_array(&encoder, &rootArray, resourceCount);
+
+        // Open the main root array
+        err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
+
+        // Open the root map in the root array
+        err = err | cbor_encoder_create_map(&rootArray, &rootMap, DISCOVERY_CBOR_RES_MAP_LEN);
+
+        // Insert Device ID into the root map
+        err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_DEVICE_ID,
+                sizeof(OC_RSRVD_DEVICE_ID) - 1);
+        err = err | cbor_encode_byte_string(&rootMap, payload->sid, UUID_SIZE);
+
+
+        // Insert Links into the root map.
+        CborEncoder linkArray = {};
+        err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_LINKS,
+                    sizeof(OC_RSRVD_LINKS) - 1);
+        err = err | cbor_encoder_create_array(&rootMap, &linkArray, resourceCount);
 
         for(size_t i = 0; i < resourceCount; ++i)
         {
-            CborEncoder map;
+            CborEncoder resourceMapElement = {};
             OCResourcePayload* resource = OCDiscoveryPayloadGetResource(payload, i);
             if(!resource)
             {
@@ -300,97 +334,85 @@ static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* o
                 return OC_STACK_INVALID_PARAM;
             }
 
-            err = err | cbor_encoder_create_map(&rootArray, &map, DISCOVERY_CBOR_RES_MAP_LEN);
+            // resource map inside the links array.
+            err = err | cbor_encoder_create_map(&linkArray, &resourceMapElement,
+                DISCOVERY_CBOR_LINKS_MAP_LEN);
+
+            // Below are insertions of the resource properties into the map.
+            // Uri
+            err = err | AddTextStringToMap(&resourceMapElement, OC_RSRVD_HREF,
+                        sizeof(OC_RSRVD_HREF) - 1,
+                        resource->uri);
+            // Resource Type
+            if (resource->types)
+            {
+                char* joinedTypes = OCStringLLJoin(resource->types);
+                if (joinedTypes)
+                {
+                    err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_RESOURCE_TYPE,
+                            sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+                    err = err | cbor_encode_text_string(&resourceMapElement, joinedTypes,
+                            strlen(joinedTypes));
+                    OICFree(joinedTypes);
+                }
+                else
+                {
+                    return OC_STACK_NO_MEMORY;
+                }
+            }
+            // Interface Types
+            if (resource->interfaces)
+            {
+                char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
+                if (joinedInterfaces)
+                {
+                    err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_INTERFACE,
+                            sizeof(OC_RSRVD_INTERFACE) - 1);
+                    err = err | cbor_encode_text_string(&resourceMapElement, joinedInterfaces,
+                            strlen(joinedInterfaces));
+                    OICFree(joinedInterfaces);
+                }
+                else
+                {
+                    return OC_STACK_NO_MEMORY;
+                }
+            }
+
+            // Policy
+            CborEncoder policyMap;
+            err = err | cbor_encode_text_string(&resourceMapElement, OC_RSRVD_POLICY,
+                    sizeof(OC_RSRVD_POLICY) - 1);
+            err = err | cbor_encoder_create_map(&resourceMapElement, &policyMap, CborIndefiniteLength);
 
-            // Device ID
-            err = err | cbor_encode_text_string(&map, OC_RSRVD_DEVICE_ID,
-                    sizeof(OC_RSRVD_DEVICE_ID) - 1);
-            err = err | cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
+            // Bitmap
+            err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
+                    sizeof(OC_RSRVD_BITMAP) - 1);
+            err = err | cbor_encode_uint(&policyMap, resource->bitmap);
 
+            if(resource->secure)
             {
-                CborEncoder linkArray;
-                err = err | cbor_encode_text_string(&map, OC_RSRVD_LINKS, sizeof(OC_RSRVD_LINKS) -1);
-                err = err | cbor_encoder_create_array(&map, &linkArray, CborIndefiniteLength);
+                err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+                        sizeof(OC_RSRVD_SECURE) - 1);
+                err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
 
-                // Link Map
+                if(resource->port != 0)
                 {
-                    CborEncoder linkMap;
-                    err = err | cbor_encoder_create_map(&linkArray, &linkMap, DISCOVERY_CBOR_LINKS_MAP_LEN);
-
-                    // Uri
-                    err = err | AddTextStringToMap(&linkMap, OC_RSRVD_HREF,
-                            sizeof(OC_RSRVD_HREF) - 1,
-                            resource->uri);
-                    // Resource Type
-                    if (resource->types)
-                    {
-                        char* joinedTypes = OCStringLLJoin(resource->types);
-                        if (joinedTypes)
-                        {
-                            err = err | cbor_encode_text_string(&linkMap, OC_RSRVD_RESOURCE_TYPE,
-                                    sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
-                            err = err | cbor_encode_text_string(&linkMap, joinedTypes,
-                                    strlen(joinedTypes));
-                            OICFree(joinedTypes);
-                        }
-                        else
-                        {
-                            return OC_STACK_NO_MEMORY;
-                        }
-                    }
-                    // Interface Types
-                    if (resource->interfaces)
-                    {
-                        char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
-                        if (joinedInterfaces)
-                        {
-                            err = err | cbor_encode_text_string(&linkMap, OC_RSRVD_INTERFACE,
-                                    sizeof(OC_RSRVD_INTERFACE) - 1);
-                            err = err | cbor_encode_text_string(&linkMap, joinedInterfaces,
-                                    strlen(joinedInterfaces));
-                            OICFree(joinedInterfaces);
-                        }
-                        else
-                        {
-                            return OC_STACK_NO_MEMORY;
-                        }
-                    }
-                    // Policy
-                    {
-                        CborEncoder policyMap;
-                        err = err | cbor_encode_text_string(&linkMap, OC_RSRVD_POLICY,
-                                sizeof(OC_RSRVD_POLICY) - 1);
-                        err = err | cbor_encoder_create_map(&linkMap, &policyMap, CborIndefiniteLength);
-
-                        // Bitmap
-                        err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
-                                sizeof(OC_RSRVD_BITMAP) - 1);
-                        err = err | cbor_encode_uint(&policyMap, resource->bitmap);
-
-                        if(resource->secure)
-                        {
-                            err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
-                                    sizeof(OC_RSRVD_SECURE) - 1);
-                            err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
-
-                            if(resource->port != 0)
-                            {
-                                err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
-                                        sizeof(OC_RSRVD_HOSTING_PORT) - 1);
-                                err = err | cbor_encode_uint(&policyMap, resource->port);
-                            }
-                        }
-
-                        err = err | cbor_encoder_close_container(&linkMap, &policyMap);
-                    }
-                    // Close
-                    err = err | cbor_encoder_close_container(&linkArray, &linkMap);
+                    err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
+                            sizeof(OC_RSRVD_HOSTING_PORT) - 1);
+                    err = err | cbor_encode_uint(&policyMap, resource->port);
                 }
-                err = err | cbor_encoder_close_container(&map, &linkArray);
             }
-            err = err | cbor_encoder_close_container(&rootArray, &map);
+
+            err = err | cbor_encoder_close_container(&resourceMapElement, &policyMap);
+
+            // Finsihed encoding a resource, close the map.
+            err = err | cbor_encoder_close_container(&linkArray, &resourceMapElement);
         }
-        // Close main array
+        // Close links array inside the root map.
+        err = err | cbor_encoder_close_container(&rootMap, &linkArray);
+        // close root map inside the root array.
+        err = err | cbor_encoder_close_container(&rootArray, &rootMap);
+        // Close the final root array.
         err = err | cbor_encoder_close_container(&encoder, &rootArray);
     }
 
@@ -407,53 +429,30 @@ static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayl
     int64_t err = 0;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
-    CborEncoder rootArray;
-    err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
+    CborEncoder repMap;
+    err = err | cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
 
-    {
-        CborEncoder map;
-        err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+    // Device ID
+    err = err | cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
+            sizeof(OC_RSRVD_DEVICE_ID) - 1);
+    err = err | cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
 
-        // uri
-        err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
-                payload->uri);
+    // Device Name
+    err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
+            sizeof(OC_RSRVD_DEVICE_NAME) - 1,
+            payload->deviceName);
 
-        // Rep Map
-        {
-            CborEncoder repMap;
-            err = err | cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
-                    sizeof(OC_RSRVD_REPRESENTATION) - 1);
-            err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
-
-            // Device ID
-            err = err | cbor_encode_text_string(&repMap, OC_RSRVD_DEVICE_ID,
-                    sizeof(OC_RSRVD_DEVICE_ID) - 1);
-            err = err | cbor_encode_byte_string(&repMap, payload->sid, UUID_SIZE);
-
-            // Device Name
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DEVICE_NAME,
-                    sizeof(OC_RSRVD_DEVICE_NAME) - 1,
-                    payload->deviceName);
-
-            // Device Spec Version
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
-                    sizeof(OC_RSRVD_SPEC_VERSION) - 1,
-                    payload->specVersion);
-
-            // Device data Model Version
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
-                    sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
-                    payload->dataModelVersion);
-
-            err = err | cbor_encoder_close_container(&map, &repMap);
-        }
+    // Device Spec Version
+    err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SPEC_VERSION,
+            sizeof(OC_RSRVD_SPEC_VERSION) - 1,
+            payload->specVersion);
 
-        // Close Map
-        err = err | cbor_encoder_close_container(&rootArray, &map);
-    }
+    // Device data Model Version
+    err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_DATA_MODEL_VERSION,
+            sizeof(OC_RSRVD_DATA_MODEL_VERSION) - 1,
+            payload->dataModelVersion);
 
-    // Close main array
-    err = err | cbor_encoder_close_container(&encoder, &rootArray);
+    err = err | cbor_encoder_close_container(&encoder, &repMap);
 
     return checkError(err, &encoder, outPayload, size);
 }
@@ -465,87 +464,69 @@ static int64_t OCConvertPlatformPayload(OCPlatformPayload* payload, uint8_t* out
     int64_t err = 0;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
-    CborEncoder rootArray;
-    err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
     {
-        CborEncoder map;
-        err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
-
-        // uri
-        err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF, sizeof(OC_RSRVD_HREF) - 1,
-                payload->uri);
-
-        // Rep Map
-        {
-            CborEncoder repMap;
-            err = err | cbor_encode_text_string(&map, OC_RSRVD_REPRESENTATION,
-                    sizeof(OC_RSRVD_REPRESENTATION) - 1);
-            err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
-
-            // Platform ID
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
-                    sizeof(OC_RSRVD_PLATFORM_ID) - 1,
-                    payload->info.platformID);
-
-            // MFG Name
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
-                    sizeof(OC_RSRVD_MFG_NAME) - 1,
-                    payload->info.manufacturerName);
-
-            // MFG Url
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
-                    sizeof(OC_RSRVD_MFG_URL) - 1,
-                    payload->info.manufacturerUrl);
-
-            // Model Num
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
-                    sizeof(OC_RSRVD_MODEL_NUM) - 1,
-                    payload->info.modelNumber);
-
-            // Date of Mfg
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
-                    sizeof(OC_RSRVD_MFG_DATE) - 1,
-                    payload->info.dateOfManufacture);
-
-            // Platform Version
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
-                    sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
-                    payload->info.platformVersion);
-
-            // OS Version
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
-                    sizeof(OC_RSRVD_OS_VERSION) - 1,
-                    payload->info.operatingSystemVersion);
-
-            // Hardware Version
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
-                    sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
-                    payload->info.hardwareVersion);
-
-            // Firmware Version
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
-                    sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
-                    payload->info.firmwareVersion);
-
-            // Support URL
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
-                    sizeof(OC_RSRVD_SUPPORT_URL) - 1,
-                    payload->info.supportUrl);
-
-            // System Time
-            err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
-                    sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
-                    payload->info.systemTime);
-            err = err | cbor_encoder_close_container(&map, &repMap);
-        }
+        CborEncoder repMap;
+        err = err | cbor_encoder_create_map(&encoder, &repMap, CborIndefiniteLength);
+
+        // Platform ID
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_ID,
+                sizeof(OC_RSRVD_PLATFORM_ID) - 1,
+                payload->info.platformID);
+
+        // MFG Name
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_NAME,
+                sizeof(OC_RSRVD_MFG_NAME) - 1,
+                payload->info.manufacturerName);
+
+        // MFG Url
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_URL,
+                sizeof(OC_RSRVD_MFG_URL) - 1,
+                payload->info.manufacturerUrl);
+
+        // Model Num
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MODEL_NUM,
+                sizeof(OC_RSRVD_MODEL_NUM) - 1,
+                payload->info.modelNumber);
+
+        // Date of Mfg
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_MFG_DATE,
+                sizeof(OC_RSRVD_MFG_DATE) - 1,
+                payload->info.dateOfManufacture);
+
+        // Platform Version
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_PLATFORM_VERSION,
+                sizeof(OC_RSRVD_PLATFORM_VERSION) - 1,
+                payload->info.platformVersion);
+
+        // OS Version
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_OS_VERSION,
+                sizeof(OC_RSRVD_OS_VERSION) - 1,
+                payload->info.operatingSystemVersion);
+
+        // Hardware Version
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_HARDWARE_VERSION,
+                sizeof(OC_RSRVD_HARDWARE_VERSION) - 1,
+                payload->info.hardwareVersion);
+
+        // Firmware Version
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_FIRMWARE_VERSION,
+                sizeof(OC_RSRVD_FIRMWARE_VERSION) - 1,
+                payload->info.firmwareVersion);
+
+        // Support URL
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SUPPORT_URL,
+                sizeof(OC_RSRVD_SUPPORT_URL) - 1,
+                payload->info.supportUrl);
+
+        // System Time
+        err = err | ConditionalAddTextStringToMap(&repMap, OC_RSRVD_SYSTEM_TIME,
+                sizeof(OC_RSRVD_SYSTEM_TIME) - 1,
+                payload->info.systemTime);
 
         // Close Map
-        err = err | cbor_encoder_close_container(&rootArray, &map);
+        err = err | cbor_encoder_close_container(&encoder, &repMap);
     }
 
-    // Close main array
-    err = err | cbor_encoder_close_container(&encoder, &rootArray);
-
     return checkError(err, &encoder, outPayload, size);
 }
 
@@ -586,7 +567,7 @@ static int64_t OCConvertArrayItem(CborEncoder* array, const OCRepPayloadValueArr
             }
             else
             {
-                err = OCConvertSingleRepPayload(array, valArray->objArray[index]);
+                err = OCConvertRepMap(array, valArray->objArray[index]);
             }
             break;
         case OCREP_PROP_ARRAY:
@@ -645,117 +626,64 @@ static int64_t OCConvertArray(CborEncoder* parent, const OCRepPayloadValueArray*
     return err;
 }
 
-static int64_t OCConvertSingleRepPayload(CborEncoder* parent, const OCRepPayload* payload)
+static int64_t OCConvertRepMap(CborEncoder *map, const OCRepPayload* payload)
 {
     int64_t err = 0;
-    CborEncoder map;
-    err = err | cbor_encoder_create_map(parent, &map, CborIndefiniteLength);
-
-    // Uri
-    err = err | ConditionalAddTextStringToMap(&map, OC_RSRVD_HREF,
-            sizeof(OC_RSRVD_HREF) - 1,
-            payload->uri);
-
-    // Prop Map
-    // resource types, interfaces
-    if(payload->types || payload->interfaces)
-    {
-        OC_LOG(INFO, TAG, "Payload has types or interfaces");
-        err = err | cbor_encode_text_string(&map,
-                OC_RSRVD_PROPERTY,
-                sizeof(OC_RSRVD_PROPERTY) - 1);
-        CborEncoder propMap;
-        err = err | cbor_encoder_create_map(&map, &propMap, 2);
-
-        if (payload->types)
-        {
-            char* joinedTypes = OCStringLLJoin(payload->types);
-            if (joinedTypes)
-            {
-                err = err | cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
-                        sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
-                err = err | cbor_encode_text_string(&propMap, joinedTypes,
-                        strlen(joinedTypes));
-                OICFree(joinedTypes);
-            }
-            else
-            {
-                return OC_STACK_NO_MEMORY;
-            }
-        }
-        if (payload->interfaces)
-        {
-            char* joinedInterfaces = OCStringLLJoin(payload->interfaces);
-            if (joinedInterfaces)
-            {
-                err = err | cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
-                        sizeof(OC_RSRVD_INTERFACE) - 1);
-                err = err | cbor_encode_text_string(&propMap, joinedInterfaces,
-                        strlen(joinedInterfaces));
-                OICFree(joinedInterfaces);
-            }
-            else
-            {
-                return OC_STACK_NO_MEMORY;
-            }
-        }
-        err = err | cbor_encoder_close_container(&map, &propMap);
-    }
+    CborEncoder repMap;
+    err = err | cbor_encoder_create_map(map, &repMap, CborIndefiniteLength);
+    err = err | OCConvertSingleRepPayload(&repMap, payload);
+    err = err | cbor_encoder_close_container(map, &repMap);
+    return err;
+}
 
-    // Rep Map
+static int64_t OCConvertSingleRepPayload(CborEncoder* repMap, const OCRepPayload* payload)
+{
+    int64_t err = 0;
+    OCRepPayloadValue* value = payload->values;
+    while(value)
     {
-        CborEncoder repMap;
-        err = err | cbor_encode_text_string(&map,
-                OC_RSRVD_REPRESENTATION,
-                sizeof(OC_RSRVD_REPRESENTATION) - 1);
-        err = err | cbor_encoder_create_map(&map, &repMap, CborIndefiniteLength);
-        OCRepPayloadValue* value = payload->values;
-        while(value)
+        err = err | cbor_encode_text_string(repMap,
+                value->name,
+                strlen(value->name));
+        switch(value->type)
         {
-            err = err | cbor_encode_text_string(&repMap,
-                    value->name,
-                    strlen(value->name));
-            switch(value->type)
-            {
-                case OCREP_PROP_NULL:
-                    err = err | cbor_encode_null(&repMap);
-                    break;
-                case OCREP_PROP_INT:
-                    err = err | cbor_encode_int(&repMap,
-                            value->i);
-                    break;
-                case OCREP_PROP_DOUBLE:
-                    err = err | cbor_encode_double(&repMap,
-                            value->d);
-                    break;
-                case OCREP_PROP_BOOL:
-                    err = err | cbor_encode_boolean(&repMap,
-                            value->b);
-                    break;
-                case OCREP_PROP_STRING:
-                    err = err | cbor_encode_text_string(&repMap,
-                            value->str, strlen(value->str));
-                    break;
-                case OCREP_PROP_OBJECT:
-                    err = err | OCConvertSingleRepPayload(&repMap, value->obj);
-                    break;
-                case OCREP_PROP_ARRAY:
-                    err = err | OCConvertArray(&repMap, &value->arr);
-                    break;
-                default:
-                    OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
-                            value->type);
-                    break;
-            }
-            value = value->next;
+            case OCREP_PROP_NULL:
+                err = err | cbor_encode_null(repMap);
+                break;
+            case OCREP_PROP_INT:
+                err = err | cbor_encode_int(repMap,
+                        value->i);
+                break;
+            case OCREP_PROP_DOUBLE:
+                err = err | cbor_encode_double(repMap,
+                        value->d);
+                break;
+            case OCREP_PROP_BOOL:
+                err = err | cbor_encode_boolean(repMap,
+                        value->b);
+                break;
+            case OCREP_PROP_STRING:
+                err = err | cbor_encode_text_string(repMap,
+                        value->str, strlen(value->str));
+                break;
+            case OCREP_PROP_BYTE_STRING:
+                err = err | cbor_encode_byte_string(repMap,
+                        value->ocByteStr.bytes, value->ocByteStr.len);
+                break;
+            case OCREP_PROP_OBJECT:
+                err = err | OCConvertRepMap(repMap, value->obj);
+                break;
+            case OCREP_PROP_ARRAY:
+                err = err | OCConvertArray(repMap, &value->arr);
+                break;
+            default:
+                OC_LOG_V(ERROR, TAG, "Invalid Prop type: %d",
+                        value->type);
+                break;
         }
-
-        err = err | cbor_encoder_close_container(&map, &repMap);
+        value = value->next;
     }
 
-    // Close Map
-    err = err | cbor_encoder_close_container(parent, &map);
-
     return err;
 }
 
@@ -765,17 +693,51 @@ static int64_t OCConvertRepPayload(OCRepPayload* payload, uint8_t* outPayload, s
     int64_t err = 0;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
-    CborEncoder rootArray;
-    err = err | cbor_encoder_create_array(&encoder, &rootArray, CborIndefiniteLength);
+    CborEncoder rootMap;
+    err = err | cbor_encoder_create_map(&encoder, &rootMap, CborIndefiniteLength);
+
+    if (payload->types)
+    {
+        OC_LOG(INFO, TAG, "Payload has types or interfaces");
+        char* joinedTypes = OCStringLLJoin(payload->types);
+        if (joinedTypes)
+        {
+            err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_RESOURCE_TYPE,
+                    sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+            err = err | cbor_encode_text_string(&rootMap, joinedTypes,
+                    strlen(joinedTypes));
+            OICFree(joinedTypes);
+        }
+        else
+        {
+            return OC_STACK_NO_MEMORY;
+        }
+    }
+    if (payload->interfaces)
+    {
+        char* joinedInterfaces = OCStringLLJoin(payload->interfaces);
+        if (joinedInterfaces)
+        {
+            err = err | cbor_encode_text_string(&rootMap, OC_RSRVD_INTERFACE,
+                    sizeof(OC_RSRVD_INTERFACE) - 1);
+            err = err | cbor_encode_text_string(&rootMap, joinedInterfaces,
+                    strlen(joinedInterfaces));
+            OICFree(joinedInterfaces);
+        }
+        else
+        {
+            return OC_STACK_NO_MEMORY;
+        }
+    }
 
     while(payload != NULL && (err == 0 || err == CborErrorOutOfMemory))
     {
-        err = err | OCConvertSingleRepPayload(&rootArray, payload);
+        err = err | OCConvertSingleRepPayload(&rootMap, payload);
         payload = payload->next;
     }
 
     // Close main array
-    err = err | cbor_encoder_close_container(&encoder, &rootArray);
+    err = err | cbor_encoder_close_container(&encoder, &rootMap);
 
     return checkError(err, &encoder, outPayload, size);
 }
@@ -787,12 +749,8 @@ static int64_t OCConvertPresencePayload(OCPresencePayload* payload,
     int64_t err = 0;
 
     cbor_encoder_init(&encoder, outPayload, *size, 0);
-    CborEncoder rootArray;
-
-    err = err | cbor_encoder_create_array(&encoder, &rootArray, 1);
-
     CborEncoder map;
-    err = err | cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+    err = err | cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
 
     // Sequence Number
     err = err | cbor_encode_text_string(&map,
@@ -819,8 +777,7 @@ static int64_t OCConvertPresencePayload(OCPresencePayload* payload,
     }
 
     // Close Map
-    err = err | cbor_encoder_close_container(&rootArray, &map);
-    err = err | cbor_encoder_close_container(&encoder, &rootArray);
+    err = err | cbor_encoder_close_container(&encoder, &map);
 
     return checkError(err, &encoder, outPayload, size);
 }
index d2aaf6a..4dc71ee 100644 (file)
@@ -63,45 +63,29 @@ OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType payloadType,
         return OC_STACK_ERROR;
     }
 
-    if(!cbor_value_is_array(&rootValue))
-    {
-        OC_LOG_V(ERROR, TAG, "CBOR payload root object is not an array :%x", rootValue.type);
-        return OC_STACK_MALFORMED_RESPONSE;
-    }
-
-    CborValue arrayValue;
-    // enter the array
-    err = err || cbor_value_enter_container(&rootValue, &arrayValue);
-
-    if(err)
-    {
-        OC_LOG_V(ERROR, TAG, "CBOR payload parse failed :%d", err);
-        return OC_STACK_MALFORMED_RESPONSE;
-    }
-
     OCStackResult result = OC_STACK_ERROR;
     switch(payloadType)
     {
         case PAYLOAD_TYPE_DISCOVERY:
-            result = OCParseDiscoveryPayload(outPayload, &arrayValue);
+            result = OCParseDiscoveryPayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_DEVICE:
-            result = OCParseDevicePayload(outPayload, &arrayValue);
+            result = OCParseDevicePayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_PLATFORM:
-            result = OCParsePlatformPayload(outPayload, &arrayValue);
+            result = OCParsePlatformPayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_REPRESENTATION:
-            result = OCParseRepPayload(outPayload, &arrayValue);
+            result = OCParseRepPayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_PRESENCE:
-            result = OCParsePresencePayload(outPayload, &arrayValue);
+            result = OCParsePresencePayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_SECURITY:
-            result = OCParseSecurityPayload(outPayload, &arrayValue);
+            result = OCParseSecurityPayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_RD:
-            result = OCRDCborToPayload(&arrayValue, outPayload);
+            result = OCRDCborToPayload(&rootValue, outPayload);
             break;
         default:
             OC_LOG_V(ERROR, TAG, "ParsePayload Type default: %d", payloadType);
@@ -109,15 +93,7 @@ OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType payloadType,
             break;
     }
 
-    if(result == OC_STACK_OK)
-    {
-        err = err || cbor_value_leave_container(&rootValue, &arrayValue);
-        if(err != CborNoError)
-        {
-            return OC_STACK_MALFORMED_RESPONSE;
-        }
-    }
-    else
+    if(result != OC_STACK_OK)
     {
         OC_LOG_V(INFO, TAG, "Finished parse payload, result is %d", result);
     }
@@ -127,7 +103,7 @@ OCStackResult OCParsePayload(OCPayload** outPayload, OCPayloadType payloadType,
 
 void OCFreeOCStringLL(OCStringLL* ll);
 
-static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* rootValue)
 {
     if (!outPayload)
     {
@@ -136,25 +112,12 @@ static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* a
 
     bool err = false;
     char * securityData = NULL;
+    CborValue map;
+    size_t len;
 
-    if(cbor_value_is_map(arrayVal))
-    {
-        CborValue curVal;
-        err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
-
-        if(cbor_value_is_valid(&curVal))
-        {
-            size_t len;
-            err = err || cbor_value_dup_text_string(&curVal, &securityData, &len, NULL);
-        }
-    }
-    else
-    {
-        OC_LOG(ERROR, TAG, "Cbor main value not a map");
-        return OC_STACK_MALFORMED_RESPONSE;
-    }
-
-    err = err || cbor_value_advance(arrayVal);
+    err = err || cbor_value_enter_container(rootValue, &map);
+    err = err || cbor_value_dup_text_string(&map, &securityData, &len, NULL);
+    err = err || cbor_value_leave_container(rootValue, &map);
 
     if(err)
     {
@@ -188,7 +151,7 @@ static char* InPlaceStringTrim(char* str)
     return str;
 }
 
-static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue* rootValue)
 {
     if (!outPayload)
     {
@@ -197,6 +160,8 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue*
 
     bool err = false;
     OCResourcePayload* resource = NULL;
+    uint16_t resourceCount = 0;
+    CborValue resourceMap = {};
 
     OCDiscoveryPayload* out = OCDiscoveryPayloadCreate();
     if(!out)
@@ -204,271 +169,219 @@ static OCStackResult OCParseDiscoveryPayload(OCPayload** outPayload, CborValue*
         return OC_STACK_NO_MEMORY;
     }
 
-    if (cbor_value_is_array(arrayVal))
+    // Root value is already inside the main root array
+    CborValue rootMap = {};
+
+    // Enter the main root map
+    err = err || cbor_value_enter_container(rootValue, &rootMap);
+    // Look for DI
+    CborValue curVal = {};
+    err = cbor_value_map_find_value(&rootMap, OC_RSRVD_DEVICE_ID, &curVal);
+    if (CborNoError != err)
     {
-        OCLinksPayload *linksPayload = NULL;
-        OCTagsPayload *tagsPayload = NULL;
-        while (cbor_value_is_container(arrayVal))
-        {
-            linksPayload = NULL;
-            tagsPayload = NULL;
-            CborValue colResources;
-            CborError cborFindResult = cbor_value_enter_container(arrayVal, &colResources);
-            if (CborNoError != cborFindResult)
-            {
-                goto cbor_error;
-            }
+        OC_LOG(ERROR, TAG, "Cbor find value failed.");
+        goto malformed_cbor;
+    }
+    size_t len;
+    err = cbor_value_dup_byte_string(&curVal, &(out->sid), &len, NULL);
 
-            if (OC_STACK_OK != OCTagsCborToPayload(&colResources, &tagsPayload))
-            {
-                OC_LOG(ERROR, TAG, "Tags cbor parsing failed.");
-                OCFreeTagsResource(tagsPayload);
-                goto cbor_error;
-            }
+    // Look for Links which will have an array as the value
+    err = cbor_value_map_find_value(&rootMap, OC_RSRVD_LINKS, &curVal);
+    if (CborNoError != err)
+    {
+        OC_LOG(ERROR, TAG, "Cbor find value failed.");
+        goto malformed_cbor;
+    }
 
-            if (OC_STACK_OK != OCLinksCborToPayload(&colResources, &linksPayload))
-            {
-                OC_LOG(ERROR, TAG, "Links cbor parsing failed.");
-                OCFreeTagsResource(tagsPayload);
-                OCFreeLinksResource(linksPayload);
-                goto cbor_error;
-            }
+    // Enter the links array and start iterating through the array processing
+    // each resource which shows up as a map.
+    err = err || cbor_value_enter_container(&curVal, &resourceMap);
 
-            if (OC_STACK_OK != OCDiscoveryCollectionPayloadAddResource(out, tagsPayload, linksPayload))
-            {
-                OC_LOG(ERROR, TAG, "Memory allocation failed");
-                OCFreeLinksResource(linksPayload);
-                OCFreeTagsResource(tagsPayload);
-                OCDiscoveryPayloadDestroy(out);
-                return OC_STACK_NO_MEMORY;
-            }
-            if (CborNoError != cbor_value_advance(arrayVal))
-            {
-                OC_LOG(ERROR, TAG, "Cbor value advanced failed.");
-                goto cbor_error;
-            }
-        }
-    }
-    if (cbor_value_is_map(arrayVal))
+    while (cbor_value_is_map(&resourceMap))
     {
-        size_t resourceCount = 0;
-        while (cbor_value_is_map(arrayVal))
+        resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+        if(!resource)
         {
-            resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
-            if(!resource)
-            {
-                OC_LOG(ERROR, TAG, "Memory allocation failed");
-                OCDiscoveryPayloadDestroy(out);
-                return OC_STACK_NO_MEMORY;
-            }
-            CborValue curVal;
-            // DI
-            err = cbor_value_map_find_value(arrayVal, OC_RSRVD_DEVICE_ID, &curVal);
-            if (CborNoError != err)
-            {
-                OC_LOG(ERROR, TAG, "Cbor find value failed.");
-                goto malformed_cbor;
-            }
-            size_t len;
-            err = cbor_value_dup_byte_string(&curVal, &(resource->sid), &len, NULL);
+            OC_LOG(ERROR, TAG, "Memory allocation failed");
+            OCDiscoveryPayloadDestroy(out);
+            return OC_STACK_NO_MEMORY;
+        }
+
+        // Uri
+        CborValue uriVal = {};
+        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_HREF, &uriVal);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding href type failed.");
+            goto malformed_cbor;
+        }
+        err = cbor_value_dup_text_string(&uriVal, &(resource->uri), &len, NULL);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding href value failed.");
+            goto malformed_cbor;
+        }
+        // ResourceTypes
+        CborValue rtVal = {};
+        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_RESOURCE_TYPE, &rtVal);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding rt type failed.");
+            goto malformed_cbor;
+        }
+        if (cbor_value_is_text_string(&rtVal))
+        {
+            char* input = NULL;
+            char* savePtr;
+            err = cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
             if (CborNoError != err)
             {
-                OC_LOG(ERROR, TAG, "Cbor di finding failed.");
+                OC_LOG(ERROR, TAG, "Cbor finding rt value failed.");
                 goto malformed_cbor;
             }
-            // Links TAG
+            if (input)
             {
-                CborValue linkArray;
-                err = cbor_value_map_find_value(arrayVal, OC_RSRVD_LINKS, &linkArray);
-                if (CborNoError != err)
-                {
-                    OC_LOG(ERROR, TAG, "Cbor links finding failed.");
-                    goto malformed_cbor;
-                }
-                CborValue linkMap;
-                err = cbor_value_enter_container(&linkArray, &linkMap);
-                if (CborNoError != err)
-                {
-                    OC_LOG(ERROR, TAG, "Cbor entering map failed.");
-                    goto malformed_cbor;
-                }
-                // Uri
-                err = cbor_value_map_find_value(&linkMap, OC_RSRVD_HREF, &curVal);
-                if (CborNoError != err)
-                {
-                    OC_LOG(ERROR, TAG, "Cbor finding href type failed.");
-                    goto malformed_cbor;
-                }
-                err = cbor_value_dup_text_string(&curVal, &(resource->uri), &len, NULL);
-                if (CborNoError != err)
-                {
-                    OC_LOG(ERROR, TAG, "Cbor finding href value failed.");
-                    goto malformed_cbor;
-                }
-                // ResourceTypes
-                CborValue rtVal;
-                err = cbor_value_map_find_value(&linkMap, OC_RSRVD_RESOURCE_TYPE, &rtVal);
-                if (CborNoError != err)
-                {
-                    OC_LOG(ERROR, TAG, "Cbor finding rt type failed.");
-                    goto malformed_cbor;
-                }
-                if (cbor_value_is_text_string(&rtVal))
+                char* curPtr = strtok_r(input, " ", &savePtr);
+
+                while (curPtr)
                 {
-                    char* input = NULL;
-                    char* savePtr;
-                    err = cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
-                    if (CborNoError != err)
-                    {
-                        OC_LOG(ERROR, TAG, "Cbor finding rt value failed.");
-                        goto malformed_cbor;
-                    }
-                    if (input)
+                    char* trimmed = InPlaceStringTrim(curPtr);
+                    if (trimmed[0] !='\0')
                     {
-                        char* curPtr = strtok_r(input, " ", &savePtr);
-
-                        while (curPtr)
+                        if (!OCResourcePayloadAddResourceType(resource, trimmed))
                         {
-                            char* trimmed = InPlaceStringTrim(curPtr);
-                            if (trimmed[0] !='\0')
-                            {
-                                if (!OCResourcePayloadAddResourceType(resource, trimmed))
-                                {
-                                    OICFree(resource->uri);
-                                    OICFree(resource->sid);
-                                    OCFreeOCStringLL(resource->types);
-                                    OICFree(resource);
-                                    OCDiscoveryPayloadDestroy(out);
-                                    return OC_STACK_NO_MEMORY;
-                                }
-                            }
-                            curPtr = strtok_r(NULL, " ", &savePtr);
+                            OICFree(resource->uri);
+                            OCFreeOCStringLL(resource->types);
+                            OICFree(resource);
+                            OCDiscoveryPayloadDestroy(out);
+                            return OC_STACK_NO_MEMORY;
                         }
-                        OICFree(input);
                     }
+                    curPtr = strtok_r(NULL, " ", &savePtr);
                 }
+                OICFree(input);
+            }
+        }
 
-                // Interface Types
-                CborValue ifVal;
-                err = cbor_value_map_find_value(&linkMap, OC_RSRVD_INTERFACE, &ifVal);
-                if (CborNoError != err)
-                {
-                    OC_LOG(ERROR, TAG, "Cbor finding if type failed.");
-                    goto malformed_cbor;
-                }
-                if (!err && cbor_value_is_text_string(&ifVal))
-                {
-                    char* input = NULL;
-                    char* savePtr;
-                    err = cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
-                    if (CborNoError != err)
-                    {
-                        OC_LOG(ERROR, TAG, "Cbor finding if value failed.");
-                        goto malformed_cbor;
-                    }
-                    if (input)
-                    {
-                        char* curPtr = strtok_r(input, " ", &savePtr);
+        // Interface Types
+        CborValue ifVal = {};
+        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_INTERFACE, &ifVal);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding if type failed.");
+            goto malformed_cbor;
+        }
+        if (!err && cbor_value_is_text_string(&ifVal))
+        {
+            char* input = NULL;
+            char* savePtr;
+            err = cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
+            if (CborNoError != err)
+            {
+                OC_LOG(ERROR, TAG, "Cbor finding if value failed.");
+                goto malformed_cbor;
+            }
+            if (input)
+            {
+                char* curPtr = strtok_r(input, " ", &savePtr);
 
-                        while (curPtr)
-                        {
-                            char* trimmed = InPlaceStringTrim(curPtr);
-                            if (trimmed[0] !='\0')
-                            {
-                                if (!OCResourcePayloadAddInterface(resource, trimmed))
-                                {
-                                    OICFree(resource->uri);
-                                    OICFree(resource->sid);
-                                    OCFreeOCStringLL(resource->types);
-                                    OICFree(resource);
-                                    OCDiscoveryPayloadDestroy(out);
-                                    return OC_STACK_NO_MEMORY;
-                                }
-                            }
-                            curPtr = strtok_r(NULL, " ", &savePtr);
-                        }
-                        OICFree(input);
-                    }
-                }
-                // Policy
+                while (curPtr)
                 {
-                    CborValue policyMap;
-                    err = cbor_value_map_find_value(&linkMap, OC_RSRVD_POLICY, &policyMap);
-                    if (CborNoError != err)
-                    {
-                        OC_LOG(ERROR, TAG, "Cbor finding policy type failed.");
-                        goto malformed_cbor;
-                    }
-                    // Bitmap
-                    CborValue val;
-                    err = cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
-                    if (CborNoError != err)
-                    {
-                        OC_LOG(ERROR, TAG, "Cbor finding bitmap type failed.");
-                        goto malformed_cbor;
-                    }
-                    uint64_t temp = 0;
-                    err = cbor_value_get_uint64(&val, &temp);
-                    if (CborNoError != err)
-                    {
-                        OC_LOG(ERROR, TAG, "Cbor finding bitmap value failed.");
-                        goto malformed_cbor;
-                    }
-                    resource->bitmap = (uint8_t)temp;
-                    // Secure Flag
-                    err = cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
-                    if (CborNoError != err)
-                    {
-                        OC_LOG(ERROR, TAG, "Cbor finding secure type failed.");
-                        goto malformed_cbor;
-                    }
-                    if(cbor_value_is_valid(&val))
+                    char* trimmed = InPlaceStringTrim(curPtr);
+                    if (trimmed[0] !='\0')
                     {
-                        err = cbor_value_get_boolean(&val, &(resource->secure));
-                        if (CborNoError != err)
+                        if (!OCResourcePayloadAddInterface(resource, trimmed))
                         {
-                            OC_LOG(ERROR, TAG, "Cbor finding secure value failed.");
-                            goto malformed_cbor;
-                        }
-                        // Port
-                        CborValue port;
-                        err = cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
-                                        &port);
-                        if (CborNoError != err)
-                        {
-                            OC_LOG(ERROR, TAG, "Cbor finding port type failed.");
-                            goto malformed_cbor;
-                        }
-                        if(cbor_value_is_valid(&port))
-                        {
-                            err = cbor_value_get_uint64(&port, &temp);
-                            if (CborNoError != err)
-                            {
-                                OC_LOG(ERROR, TAG, "Cbor finding port value failed.");
-                                goto malformed_cbor;
-                            }
-                            resource->port = (uint16_t)temp;
+                            OICFree(resource->uri);
+                            OCFreeOCStringLL(resource->types);
+                            OICFree(resource);
+                            OCDiscoveryPayloadDestroy(out);
+                            return OC_STACK_NO_MEMORY;
                         }
                     }
+                    curPtr = strtok_r(NULL, " ", &savePtr);
                 }
+                OICFree(input);
+            }
+        }
+
+        // Policy
+        CborValue policyMap = {};
+        err = cbor_value_map_find_value(&resourceMap, OC_RSRVD_POLICY, &policyMap);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding policy type failed.");
+            goto malformed_cbor;
+        }
+        // Bitmap
+        CborValue val = {};
+        err = cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding bitmap type failed.");
+            goto malformed_cbor;
+        }
+        uint64_t temp = 0;
+        err = cbor_value_get_uint64(&val, &temp);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding bitmap value failed.");
+            goto malformed_cbor;
+        }
+        resource->bitmap = (uint8_t)temp;
+        // Secure Flag
+        err = cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor finding secure type failed.");
+            goto malformed_cbor;
+        }
+        if(cbor_value_is_valid(&val))
+        {
+            err = cbor_value_get_boolean(&val, &(resource->secure));
+            if (CborNoError != err)
+            {
+                OC_LOG(ERROR, TAG, "Cbor finding secure value failed.");
+                goto malformed_cbor;
             }
-            err = cbor_value_advance(arrayVal);
+            // Port
+            CborValue port;
+            err = cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
+                            &port);
             if (CborNoError != err)
             {
-                OC_LOG(ERROR, TAG, "Cbor advance value failed.");
+                OC_LOG(ERROR, TAG, "Cbor finding port type failed.");
                 goto malformed_cbor;
             }
-            ++resourceCount;
-            OCDiscoveryPayloadAddNewResource(out, resource);
+            if(cbor_value_is_valid(&port))
+            {
+                err = cbor_value_get_uint64(&port, &temp);
+                if (CborNoError != err)
+                {
+                    OC_LOG(ERROR, TAG, "Cbor finding port value failed.");
+                    goto malformed_cbor;
+                }
+                resource->port = (uint16_t)temp;
+            }
+        }
+
+        err = cbor_value_advance(&resourceMap);
+        if (CborNoError != err)
+        {
+            OC_LOG(ERROR, TAG, "Cbor advance value failed.");
+            goto malformed_cbor;
         }
+        ++resourceCount;
+        OCDiscoveryPayloadAddNewResource(out, resource);
     }
 
+    err = err || cbor_value_leave_container(rootValue, &resourceMap);
+
     *outPayload = (OCPayload*)out;
     return OC_STACK_OK;
 
 malformed_cbor:
     OICFree(resource->uri);
-    OICFree(resource->sid);
     OCFreeOCStringLL(resource->types);
     OCFreeOCStringLL(resource->interfaces);
     OICFree(resource);
@@ -480,7 +393,7 @@ cbor_error:
     return OC_STACK_MALFORMED_RESPONSE;
 }
 
-static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* rootValue)
 {
     if (!outPayload)
     {
@@ -489,55 +402,44 @@ static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arr
 
     bool err = false;
 
-    if(cbor_value_is_map(arrayVal))
+    if(cbor_value_is_map(rootValue))
     {
-        char* uri = NULL;
         uint8_t* sid = NULL;
         char* dname = NULL;
         char* specVer = NULL;
         char* dmVer = NULL;
-        CborValue curVal;
-         err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
-        size_t len;
-         err = err || cbor_value_dup_text_string(&curVal, &uri, &len, NULL);
 
-        // Representation
+        CborValue repVal;
+        // Device ID
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_ID, &repVal);
+        size_t len;
+        if(cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
-
-            CborValue repVal;
-            // Device ID
-            err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DEVICE_ID, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                err = err || cbor_value_dup_byte_string(&repVal, &sid, &len, NULL);
-            }
-            // Device Name
-            err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DEVICE_NAME, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                err = err || cbor_value_dup_text_string(&repVal, &dname, &len, NULL);
-            }
-            // Device Spec Version
-            err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SPEC_VERSION, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                err = err || cbor_value_dup_text_string(&repVal, &specVer, &len, NULL);
-            }
-
-            // Data Model Version
-            err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_DATA_MODEL_VERSION, &repVal);
-            if (cbor_value_is_valid(&repVal))
-            {
-                err = err || cbor_value_dup_text_string(&repVal, &dmVer, &len, NULL);
-            }
+            err = err || cbor_value_dup_byte_string(&repVal, &sid, &len, NULL);
+        }
+        // Device Name
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DEVICE_NAME, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+            err = err || cbor_value_dup_text_string(&repVal, &dname, &len, NULL);
+        }
+        // Device Spec Version
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SPEC_VERSION, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+            err = err || cbor_value_dup_text_string(&repVal, &specVer, &len, NULL);
+        }
+        // Data Model Version
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_DATA_MODEL_VERSION, &repVal);
+        if (cbor_value_is_valid(&repVal))
+        {
+            err = err || cbor_value_dup_text_string(&repVal, &dmVer, &len, NULL);
         }
 
-         err = err || cbor_value_advance(arrayVal);
+        err = err || cbor_value_advance(rootValue);
 
         if(err)
         {
-            OICFree(uri);
             OICFree(sid);
             OICFree(dname);
             OICFree(specVer);
@@ -546,9 +448,8 @@ static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arr
             return OC_STACK_MALFORMED_RESPONSE;
         }
 
-        *outPayload = (OCPayload*)OCDevicePayloadCreate(uri, sid, dname, specVer, dmVer);
+        *outPayload = (OCPayload*)OCDevicePayloadCreate(sid, dname, specVer, dmVer);
 
-        OICFree(uri);
         OICFree(sid);
         OICFree(dname);
         OICFree(specVer);
@@ -568,7 +469,7 @@ static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arr
 
 }
 
-static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* rootValue)
 {
     if (!outPayload)
     {
@@ -577,104 +478,94 @@ static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* a
 
     bool err = false;
 
-    if(cbor_value_is_map(arrayVal))
+    if(cbor_value_is_map(rootValue))
     {
-        char* uri = NULL;
         OCPlatformInfo info = {0};
-        CborValue curVal;
-         err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
-        size_t len;
-         err = err || cbor_value_dup_text_string(&curVal, &uri, &len, NULL);
 
-        // Representation
+        CborValue repVal;
+        size_t len;
+        // Platform ID
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_ID, &repVal);
+        if(cbor_value_is_valid(&repVal))
+         {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
+         }
+
+         // MFG Name
+         err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_NAME, &repVal);
+         if(cbor_value_is_valid(&repVal))
+         {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
+         }
+
+        // MFG URL
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_URL, &repVal);
+        if(cbor_value_is_valid(&repVal))
         {
-             err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_REPRESENTATION, &curVal);
-
-            CborValue repVal;
-            // Platform ID
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_PLATFORM_ID, &repVal);
-             if(cbor_value_is_valid(&repVal))
-             {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.platformID), &len, NULL);
-             }
-
-            // MFG Name
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_NAME, &repVal);
-             if(cbor_value_is_valid(&repVal))
-             {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerName), &len, NULL);
-             }
-
-            // MFG URL
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_URL, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
-            }
+             err = err || cbor_value_dup_text_string(&repVal, &(info.manufacturerUrl), &len, NULL);
+        }
 
-            // Model Num
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MODEL_NUM, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
-            }
+        // Model Num
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MODEL_NUM, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.modelNumber), &len, NULL);
+        }
 
-            // Date of Mfg
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_MFG_DATE, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len,
-                        NULL);
-            }
+        // Date of Mfg
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_MFG_DATE, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.dateOfManufacture), &len,
+                    NULL);
+        }
 
-            // Platform Version
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_PLATFORM_VERSION, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len,
-                        NULL);
-            }
+        // Platform Version
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_PLATFORM_VERSION, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.platformVersion), &len, NULL);
+        }
 
-            // OS Version
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_OS_VERSION, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion),
-                        &len, NULL);
-            }
+        // OS Version
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_OS_VERSION, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.operatingSystemVersion),
+                    &len, NULL);
+        }
 
-            // Hardware Version
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_HARDWARE_VERSION, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len,
-                        NULL);
-            }
+        // Hardware Version
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_HARDWARE_VERSION, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.hardwareVersion), &len,
+                    NULL);
+        }
 
-            // Firmware Version
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_FIRMWARE_VERSION, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len,
-                        NULL);
-            }
+        // Firmware Version
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_FIRMWARE_VERSION, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.firmwareVersion), &len,
+                    NULL);
+        }
 
-            // Support URL
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SUPPORT_URL, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
-            }
+        // Support URL
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SUPPORT_URL, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.supportUrl), &len, NULL);
+        }
 
-            // System Time
-             err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_SYSTEM_TIME, &repVal);
-            if(cbor_value_is_valid(&repVal))
-            {
-                 err = err || cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
-            }
+        // System Time
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_SYSTEM_TIME, &repVal);
+        if(cbor_value_is_valid(&repVal))
+        {
+             err = err || cbor_value_dup_text_string(&repVal, &(info.systemTime), &len, NULL);
         }
 
-         err = err || cbor_value_advance(arrayVal);
+        err = err || cbor_value_advance(rootValue);
 
         if(err)
         {
@@ -693,7 +584,7 @@ static OCStackResult OCParsePlatformPayload(OCPayload** outPayload, CborValue* a
             return OC_STACK_MALFORMED_RESPONSE;
         }
 
-        *outPayload = (OCPayload*)OCPlatformPayloadCreateAsOwner(uri, &info);
+        *outPayload = (OCPayload*)OCPlatformPayloadCreateAsOwner(&info);
 
         if(!*outPayload)
         {
@@ -838,6 +729,7 @@ static bool OCParseArrayFillArray(const CborValue* parent, size_t dimensions[MAX
 
     while (!err && i < dimensions[0] && cbor_value_is_valid(&insideArray))
     {
+        bool noAdvance = false;
         if (cbor_value_get_type(&insideArray) != CborNullType)
         {
             switch (type)
@@ -906,6 +798,7 @@ static bool OCParseArrayFillArray(const CborValue* parent, size_t dimensions[MAX
                         err = err || OCParseSingleRepPayload(&tempPl, &insideArray);
                         ((OCRepPayload**)targetArray)[i] = tempPl;
                         tempPl = NULL;
+                        noAdvance = true;
                     }
                     else
                     {
@@ -922,7 +815,10 @@ static bool OCParseArrayFillArray(const CborValue* parent, size_t dimensions[MAX
             }
         }
         ++i;
-        err = err || cbor_value_advance(&insideArray);
+        if (!noAdvance && cbor_value_is_valid(&insideArray))
+        {
+            err = err || cbor_value_advance(&insideArray);
+        }
     }
 
     return err;
@@ -1013,145 +909,103 @@ static bool OCParseArray(OCRepPayload* out, const char* name, CborValue* contain
     return err;
 }
 
-static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repParent)
+static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue *objMap)
 {
     if (!outPayload)
     {
         return false;
     }
 
-    *outPayload = OCRepPayloadCreate();
-    OCRepPayload* curPayload = *outPayload;
     bool err = false;
-    if(!*outPayload)
-    {
-        return CborErrorOutOfMemory;
-    }
-
-    size_t len;
-    CborValue curVal;
-    err = err || cbor_value_map_find_value(repParent, OC_RSRVD_HREF, &curVal);
-    if(cbor_value_is_valid(&curVal))
-    {
-        err = err || cbor_value_dup_text_string(&curVal, &curPayload->uri, &len,
-            NULL);
-    }
 
-    err = err || cbor_value_map_find_value(repParent, OC_RSRVD_PROPERTY, &curVal);
-    if(cbor_value_is_valid(&curVal))
+    if (cbor_value_is_map(objMap))
     {
-        CborValue insidePropValue = {0};
-        err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE,
-                &insidePropValue);
-
-        if(cbor_value_is_text_string(&insidePropValue))
+        if (!*outPayload)
         {
-            char* allRt = NULL;
-            err = err || cbor_value_dup_text_string(&insidePropValue, &allRt, &len, NULL);
-
-            char* savePtr;
-
-            if (allRt)
+            *outPayload = OCRepPayloadCreate();
+            if(!*outPayload)
             {
-                char* curPtr = strtok_r(allRt, " ", &savePtr);
-
-                while (curPtr)
-                {
-                    char* trimmed = InPlaceStringTrim(curPtr);
-                    if (trimmed[0] != '\0')
-                    {
-                        OCRepPayloadAddResourceType(curPayload, curPtr);
-                    }
-                    curPtr = strtok_r(NULL, " ", &savePtr);
-                }
+                return CborErrorOutOfMemory;
             }
-            OICFree(allRt);
         }
 
-        err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &insidePropValue);
-
-        if(cbor_value_is_text_string(&insidePropValue))
-        {
-            char* allIf = NULL;
-            err = err || cbor_value_dup_text_string(&insidePropValue, &allIf, &len, NULL);
-
-            char* savePtr;
-
-            if (allIf)
-            {
-                char* curPtr = strtok_r(allIf, " ", &savePtr);
-
-                while (curPtr)
-                {
-                    char* trimmed = InPlaceStringTrim(curPtr);
-                    if (trimmed[0] != '\0')
-                    {
-                        OCRepPayloadAddInterface(curPayload, curPtr);
-                    }
-                    curPtr = strtok_r(NULL, " ", &savePtr);
-                }
-            }
-            OICFree(allIf);
-        }
-    }
+        OCRepPayload* curPayload = *outPayload;
 
-    err = err || cbor_value_map_find_value(repParent, OC_RSRVD_REPRESENTATION, &curVal);
-    if(cbor_value_is_map(&curVal))
-    {
+        size_t len;
         CborValue repMap;
-        err = err || cbor_value_enter_container(&curVal, &repMap);
+        err = err || cbor_value_enter_container(objMap, &repMap);
 
         while(!err && cbor_value_is_valid(&repMap))
         {
             char* name;
             err = err || cbor_value_dup_text_string(&repMap, &name, &len, NULL);
-
             err = err || cbor_value_advance(&repMap);
 
-            int64_t intval = 0;
-            bool boolval = false;
-            char* strval = NULL;
-            double doubleval = 0;
-            OCRepPayload* pl;
-
-            switch(cbor_value_get_type(&repMap))
+            CborType type = cbor_value_get_type(&repMap);
+            switch(type)
             {
                 case CborNullType:
                     err = !OCRepPayloadSetNull(curPayload, name);
                     break;
                 case CborIntegerType:
-                    err = err || cbor_value_get_int64(&repMap, &intval);
-                    if (!err)
                     {
-                        err = !OCRepPayloadSetPropInt(curPayload, name, intval);
+                        int64_t intval = 0;
+                        err = err || cbor_value_get_int64(&repMap, &intval);
+                        if (!err)
+                        {
+                            err = !OCRepPayloadSetPropInt(curPayload, name, intval);
+                        }
                     }
                     break;
                 case CborDoubleType:
-                    err = err || cbor_value_get_double(&repMap, &doubleval);
-                    if (!err)
                     {
-                        err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
+                        double doubleval = 0;
+                        err = err || cbor_value_get_double(&repMap, &doubleval);
+                        if (!err)
+                        {
+                            err = !OCRepPayloadSetPropDouble(curPayload, name, doubleval);
+                        }
                     }
                     break;
                 case CborBooleanType:
-                    err = err || cbor_value_get_boolean(&repMap, &boolval);
-                    if (!err)
                     {
-                        err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
+                        bool boolval = false;
+                        err = err || cbor_value_get_boolean(&repMap, &boolval);
+                        if (!err)
+                        {
+                            err = !OCRepPayloadSetPropBool(curPayload, name, boolval);
+                        }
                     }
                     break;
                 case CborTextStringType:
-                    err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
-                    if (!err)
                     {
-                        err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
+                        char* strval = NULL;
+                        err = err || cbor_value_dup_text_string(&repMap, &strval, &len, NULL);
+                        if (!err)
+                        {
+                            err = !OCRepPayloadSetPropStringAsOwner(curPayload, name, strval);
+                        }
+                    }
+                    break;
+                case CborByteStringType:
+                    {
+                        uint8_t* bytestrval = NULL;
+                        err = err || cbor_value_dup_byte_string(&repMap, &bytestrval, &len, NULL);
+                        if (!err)
+                        {
+                            OCByteString tmp = {.bytes = bytestrval, .len = len};
+                            err = !OCRepPayloadSetPropByteStringAsOwner(curPayload, name, &tmp);
+                        }
                     }
                     break;
                 case CborMapType:
-                    err = err || OCParseSingleRepPayload(&pl, &repMap);
-                    if (!err)
                     {
-                        err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
+                        OCRepPayload *pl = NULL;
+                        err = err || OCParseSingleRepPayload(&pl, &repMap);
+                        if (!err)
+                        {
+                            err = !OCRepPayloadSetPropObjectAsOwner(curPayload, name, pl);
+                        }
                     }
                     break;
                 case CborArrayType:
@@ -1162,35 +1016,90 @@ static bool OCParseSingleRepPayload(OCRepPayload** outPayload, CborValue* repPar
                     err = true;
             }
 
-             err = err || cbor_value_advance(&repMap);
+            if (type != CborMapType && cbor_value_is_valid(&repMap))
+            {
+                err = err || cbor_value_advance(&repMap);
+            }
             OICFree(name);
         }
-        err = err || cbor_value_leave_container(&curVal, &repMap);
-    }
 
-    if(err)
-    {
-        OCRepPayloadDestroy(*outPayload);
-        *outPayload = NULL;
+        err = err || cbor_value_leave_container(objMap, &repMap);
+
+        if(err)
+        {
+            OCRepPayloadDestroy(*outPayload);
+            *outPayload = NULL;
+        }
     }
 
     return err;
 }
-static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayVal)
+
+static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* rootMap)
 {
     if (!outPayload)
     {
         return OC_STACK_INVALID_PARAM;
     }
 
+    OCRepPayload *rootPayload = NULL;
+    OCRepPayload *curPayload = NULL;
+    OCRepPayload *temp = OCRepPayloadCreate();
+    if (!temp)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+
+    CborValue curVal;
     bool err = false;
+    size_t len;
+    err = err || cbor_value_map_find_value(rootMap, OC_RSRVD_RESOURCE_TYPE, &curVal);
+    if(cbor_value_is_text_string(&curVal))
+    {
+        char* allRt = NULL;
+        err = err || cbor_value_dup_text_string(&curVal, &allRt, &len, NULL);
+        if (allRt)
+        {
+            char* savePtr;
+            char* curPtr = strtok_r(allRt, " ", &savePtr);
+            while (curPtr)
+            {
+                char* trimmed = InPlaceStringTrim(curPtr);
+                if (trimmed[0] != '\0')
+                {
+                    OCRepPayloadAddResourceType(temp, curPtr);
+                }
+                curPtr = strtok_r(NULL, " ", &savePtr);
+            }
+        }
+        OICFree(allRt);
+    }
 
-    OCRepPayload* rootPayload = NULL;
-    OCRepPayload* curPayload = NULL;
-    OCRepPayload* temp = NULL;
-    while(!err && cbor_value_is_map(arrayVal))
+    err = err || cbor_value_map_find_value(rootMap, OC_RSRVD_INTERFACE, &curVal);
+    if(cbor_value_is_text_string(&curVal))
     {
-         err = err || OCParseSingleRepPayload(&temp, arrayVal);
+        char* allIf = NULL;
+        err = err || cbor_value_dup_text_string(&curVal, &allIf, &len, NULL);
+        if (allIf)
+        {
+            char* savePtr;
+            char* curPtr = strtok_r(allIf, " ", &savePtr);
+            while (curPtr)
+            {
+                char* trimmed = InPlaceStringTrim(curPtr);
+                if (trimmed[0] != '\0')
+                {
+                    OCRepPayloadAddInterface(temp, curPtr);
+                }
+                curPtr = strtok_r(NULL, " ", &savePtr);
+            }
+        }
+        OICFree(allIf);
+    }
+
+    while (!err && cbor_value_is_map(rootMap))
+    {
+        err = err || OCParseSingleRepPayload(&temp, rootMap);
 
         if(rootPayload == NULL)
         {
@@ -1203,8 +1112,11 @@ static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayV
             curPayload = curPayload->next;
         }
 
+        if (cbor_value_is_valid(rootMap))
+        {
+            err = err || cbor_value_advance(rootMap);
+        }
 
-         err = err || cbor_value_advance(arrayVal);
         if(err)
         {
             OCRepPayloadDestroy(rootPayload);
@@ -1218,7 +1130,7 @@ static OCStackResult OCParseRepPayload(OCPayload** outPayload, CborValue* arrayV
     return OC_STACK_OK;
 }
 
-static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* arrayVal)
+static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* rootValue)
 {
     if (!outPayload)
     {
@@ -1226,7 +1138,7 @@ static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* a
     }
 
     bool err = false;
-    if(cbor_value_is_map(arrayVal))
+    if(cbor_value_is_map(rootValue))
     {
         uint64_t seqNum = 0;
         uint64_t maxAge = 0;
@@ -1236,28 +1148,28 @@ static OCStackResult OCParsePresencePayload(OCPayload** outPayload, CborValue* a
 
         CborValue curVal;
         // Sequence Number
-        err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_NONCE, &curVal);
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_NONCE, &curVal);
         err = err || cbor_value_get_uint64(&curVal, &seqNum);
 
         // Max Age
-        err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_TTL, &curVal);
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_TTL, &curVal);
         err = err || cbor_value_get_uint64(&curVal, &maxAge);
 
         // Trigger
-        err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_TRIGGER, &curVal);
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_TRIGGER, &curVal);
         err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
         trigger = convertTriggerStringToEnum(tempStr);
         OICFree(tempStr);
         tempStr = NULL;
 
         // Resource type name
-         err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_RESOURCE_TYPE, &curVal);
+        err = err || cbor_value_map_find_value(rootValue, OC_RSRVD_RESOURCE_TYPE, &curVal);
         if(cbor_value_is_valid(&curVal))
         {
              err = err || cbor_value_dup_text_string(&curVal, &tempStr, &len, NULL);
         }
 
-        err = err || cbor_value_advance(arrayVal);
+        err = err || cbor_value_advance(rootValue);
 
         if(!err)
         {
index 20cfd72..a6b62ad 100644 (file)
@@ -615,6 +615,10 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
 
             if(payload)
             {
+                ((OCDiscoveryPayload*)payload)->sid = (uint8_t*)OICCalloc(1, UUID_SIZE);
+                memcpy(((OCDiscoveryPayload*)payload)->sid,
+                    OCGetServerInstanceID(), UUID_SIZE);
+
                 bool foundResourceAtRD = false;
                 for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
                 {
@@ -665,8 +669,7 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
         }
         else
         {
-            payload = (OCPayload*) OCDevicePayloadCreate(OC_RSRVD_DEVICE_URI,
-                    (const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
+            payload = (OCPayload*) OCDevicePayloadCreate((const uint8_t*) &deviceId->id, savedDeviceInfo.deviceName,
                     OC_SPEC_VERSION, OC_DATA_MODEL_VERSION);
             if (!payload)
             {
@@ -680,9 +683,7 @@ static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource
     }
     else if (virtualUriInRequest == OC_PLATFORM_URI)
     {
-        payload = (OCPayload*)OCPlatformPayloadCreate(
-                OC_RSRVD_PLATFORM_URI,
-                &savedPlatformInfo);
+        payload = (OCPayload*)OCPlatformPayloadCreate(&savedPlatformInfo);
         if (!payload)
         {
             discoveryResult = OC_STACK_NO_MEMORY;
index a15fcc1..6e44d4c 100644 (file)
@@ -634,10 +634,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 #ifdef RA_ADAPTER
                             , CA_ADAPTER_REMOTE_ACCESS
 #endif
-
-#ifdef TCP_ADAPTER
                             , CA_ADAPTER_TCP
-#endif
                         };
 
     size_t size = sizeof(CAConnTypes)/ sizeof(CATransportAdapter_t);
@@ -655,10 +652,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
 #ifdef RA_ADAP
                 | CA_ADAPTER_REMOTE_ACCESS
 #endif
-
-#ifdef TCP_ADAPTER
                 | CA_ADAPTER_TCP
-#endif
             );
     }
 
index 46a110b..24486de 100755 (executable)
@@ -99,6 +99,8 @@ static OCStackState stackState = OC_STACK_UNINITIALIZED;
 
 OCResource *headResource = NULL;
 static OCResource *tailResource = NULL;
+static OCResourceHandle platformResource = {0};
+static OCResourceHandle deviceResource = {0};
 #ifdef WITH_PRESENCE
 static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED;
 static PresenceResource presenceResource;
@@ -113,10 +115,7 @@ static bool gRASetInfo = false;
 #endif
 OCDeviceEntityHandler defaultDeviceHandler;
 void* defaultDeviceHandlerCallbackParameter = NULL;
-
-#ifdef TCP_ADAPTER
 static const char COAP_TCP[] = "coap+tcp:";
-#endif
 
 //-----------------------------------------------------------------------------
 // Macros
@@ -128,7 +127,7 @@ static const char COAP_TCP[] = "coap+tcp:";
              TAG, #arg " is NULL"); return (retVal); } }
 #define VERIFY_NON_NULL_NR(arg, logLevel) { if (!(arg)) { OC_LOG((logLevel), \
              TAG, #arg " is NULL"); return; } }
-#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg);\
+#define VERIFY_NON_NULL_V(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL");\
     goto exit;} }
 
 //TODO: we should allow the server to define this
@@ -1877,20 +1876,8 @@ OCStackResult OCInit1(OCMode mode, OCTransportFlags serverFlags, OCTransportFlag
         caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4|CA_IPV6);
     }
 
-#ifdef TCP_ADAPTER
-    if (!(caglobals.serverFlags & CA_IPFAMILY_MASK))
-    {
-        caglobals.serverFlags = (CATransportFlags_t)(caglobals.serverFlags|CA_IPV4);
-    }
-    if (!(caglobals.clientFlags & CA_IPFAMILY_MASK))
-    {
-        caglobals.clientFlags = (CATransportFlags_t)(caglobals.clientFlags|CA_IPV4);
-    }
-#endif
-
     defaultDeviceHandler = NULL;
     defaultDeviceHandlerCallbackParameter = NULL;
-    OCSeedRandom();
 
     result = CAResultToOCResult(CAInitialize());
     VERIFY_SUCCESS(result, OC_STACK_OK);
@@ -2130,7 +2117,6 @@ static OCStackResult ParseRequestUri(const char *fullUri,
         return OC_STACK_INVALID_URI;
     }
 
-#ifdef TCP_ADAPTER
     // process url scheme
     size_t prefixLen = slash2 - fullUri;
     bool istcp = false;
@@ -2141,7 +2127,6 @@ static OCStackResult ParseRequestUri(const char *fullUri,
             istcp = true;
         }
     }
-#endif
 
     // TODO: this logic should come in with unit tests exercising the various strings
     // processs url prefix, if any
@@ -2173,13 +2158,12 @@ static OCStackResult ParseRequestUri(const char *fullUri,
             {   // ipv4 address
                 colon = strchr(start, ':');
                 end = (colon && colon < slash) ? colon : slash;
-#ifdef TCP_ADAPTER
+
                 if (istcp)
                 {   // coap over tcp
                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_TCP);
                 }
                 else
-#endif
                 {
                     adapter = (OCTransportAdapter)(adapter | OC_ADAPTER_IP);
                     flags = (OCTransportFlags)(flags | OC_IP_USE_V4);
@@ -3743,11 +3727,44 @@ OCStackResult initResources()
             &(((OCResource *) presenceResource.handle)->resourceProperties),
             OC_ACTIVE, 0);
 #endif
-
+#ifndef WITH_ARDUINO
     if (result == OC_STACK_OK)
     {
         result = SRMInitSecureResources();
     }
+#endif
+
+    if(result == OC_STACK_OK)
+    {
+        result = OCCreateResource(&deviceResource,
+                                  OC_RSRVD_RESOURCE_TYPE_DEVICE,
+                                  OC_RSRVD_INTERFACE_DEFAULT,
+                                  OC_RSRVD_DEVICE_URI,
+                                  NULL,
+                                  NULL,
+                                  OC_DISCOVERABLE);
+        if(result == OC_STACK_OK)
+        {
+            result = BindResourceInterfaceToResource((OCResource *)deviceResource,
+                                                     OC_RSRVD_INTERFACE_READ);
+        }
+    }
+
+    if(result == OC_STACK_OK)
+    {
+        result = OCCreateResource(&platformResource,
+                                  OC_RSRVD_RESOURCE_TYPE_PLATFORM,
+                                  OC_RSRVD_INTERFACE_DEFAULT,
+                                  OC_RSRVD_PLATFORM_URI,
+                                  NULL,
+                                  NULL,
+                                  OC_DISCOVERABLE);
+        if(result == OC_STACK_OK)
+        {
+            result = BindResourceInterfaceToResource((OCResource *)platformResource,
+                                                     OC_RSRVD_INTERFACE_READ);
+        }
+    }
 
     return result;
 }
index 864cced..20d8735 100755 (executable)
@@ -713,11 +713,6 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
             {
                 OC_LOG(INFO, TAG, "Build OCAction Instance.");
 
-                if(action)
-                {
-                    OICFree(action->resourceUri);
-                    OICFree(action);
-                }
                 action = (OCAction*) OICMalloc(sizeof(OCAction));
                 VARIFY_POINTER_NULL(action, result, exit)
                 memset(action, 0, sizeof(OCAction));
index b2453b5..5a97219 100644 (file)
@@ -49,19 +49,11 @@ int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, siz
     int flags = 0;
     cbor_encoder_init(&encoder, outPayload, *size, flags);
 
-    CborEncoder rootArray;
     CborError cborEncoderResult;
-    cborEncoderResult = cbor_encoder_create_array(&encoder, &rootArray, CBOR_ROOT_ARRAY_LENGTH);
-    if (CborNoError != cborEncoderResult)
-    {
-        OC_LOG(ERROR, TAG, "Failed creating cbor array.");
-        goto cbor_error;
-    }
-
     if (rdPayload->rdDiscovery)
     {
         CborEncoder map;
-        cborEncoderResult = cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+        cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
         if (CborNoError != cborEncoderResult)
         {
             OC_LOG(ERROR, TAG, "Failed creating discovery map.");
@@ -86,7 +78,7 @@ int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, siz
             OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_RD_DISCOVERY_SEL.");
             goto cbor_error;
         }
-        cborEncoderResult = cbor_encoder_close_container(&rootArray, &map);
+        cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
         if (CborNoError != cborEncoderResult)
         {
             OC_LOG(ERROR, TAG, "Failed closing discovery map.");
@@ -96,7 +88,7 @@ int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, siz
     else if (rdPayload->rdPublish)
     {
         CborEncoder colArray;
-        cborEncoderResult = cbor_encoder_create_array(&rootArray, &colArray, CborIndefiniteLength);
+        cborEncoderResult = cbor_encoder_create_array(&encoder, &colArray, CborIndefiniteLength);
         if (CborNoError != cborEncoderResult)
         {
             OC_LOG(ERROR, TAG, "Failed creating collection array.");
@@ -118,23 +110,32 @@ int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, siz
             }
             rdPublish = rdPublish->next;
         }
-        cborEncoderResult = cbor_encoder_close_container(&rootArray, &colArray);
+        cborEncoderResult = cbor_encoder_close_container(&encoder, &colArray);
         if (CborNoError != cborEncoderResult)
         {
             OC_LOG(ERROR, TAG, "Failed closing collection array.");
             goto cbor_error;
         }
     }
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &rootArray);
-    if (CborNoError != cborEncoderResult)
+    else
     {
-        OC_LOG(ERROR, TAG, "Failed closing root array container. ");
-        goto cbor_error;
+        CborEncoder map;
+        cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+        if (CborNoError != cborEncoderResult)
+        {
+            OC_LOG(ERROR, TAG, "Failed creating discovery map.");
+            goto cbor_error;
+        }
+        cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
+        if (CborNoError != cborEncoderResult)
+        {
+            OC_LOG(ERROR, TAG, "Failed creating discovery map.");
+            goto cbor_error;
+        }
     }
-
     *size = encoder.ptr - outPayload;
-    return OC_STACK_OK;
 
+    return OC_STACK_OK;
 cbor_error:
     OICFree(outPayload);
     return OC_STACK_ERROR;
index ade8f3f..d75d459 100644 (file)
@@ -32,7 +32,7 @@ stacktest_env.PrependUnique(CPPPATH = [
                '../../security/include',
                '../../ocsocket/include',
                '../../logger/include',
-               '../../ocrandom/include',
+               '../../../c_common/ocrandom/include',
                '../../stack/include',
                '../../stack/include/internal',
                '../../connectivity/api',
index 731b203..ffb284a 100644 (file)
@@ -34,7 +34,7 @@ examples_env = lib_env.Clone()
 examples_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
-               '../csdk/ocrandom/include',
+               '../c_common/ocrandom/include',
                '../csdk/logger/include',
                '../oc_logger/include'
                ])
index 84e88e5..e7bbccb 100644 (file)
@@ -109,6 +109,10 @@ namespace OC
 
             virtual ~OCRepresentation(){}
 
+            void setDevAddr(const OCDevAddr addr);
+
+            const std::string getHost() const;
+
             OCRepPayload* getPayload() const;
 
             void addChild(const OCRepresentation&);
@@ -164,8 +168,16 @@ namespace OC
 
                 if(x!= m_values.end())
                 {
-                    val = boost::get<T>(x->second);
-                    return true;
+                    try
+                    {
+                        val = boost::get<T>(x->second);
+                        return true;
+                    }
+                    catch (boost::bad_get& e)
+                    {
+                        val = T();
+                        return false;
+                    }
                 }
                 else
                 {
@@ -189,7 +201,14 @@ namespace OC
                 auto x = m_values.find(str);
                 if(x != m_values.end())
                 {
-                    val = boost::get<T>(x->second);
+                    try
+                    {
+                        val = boost::get<T>(x->second);
+                    }
+                    catch (boost::bad_get& e)
+                    {
+                        return val;
+                    }
                 }
                 return val;
             }
@@ -224,6 +243,9 @@ namespace OC
 
             bool isNULL(const std::string& str) const;
 
+        private:
+            std::string m_host;
+
             // STL Container stuff
         public:
             class iterator;
@@ -243,7 +265,15 @@ namespace OC
                     template<typename T>
                     T getValue() const
                     {
-                        return boost::get<T>(m_values[m_attrName]);
+                        try
+                        {
+                            return boost::get<T>(m_values[m_attrName]);
+                        }
+                        catch (boost::bad_get& e)
+                        {
+                            T val = T();
+                            return val;
+                        }
                     }
 
                     std::string getValueToString() const;
index b112af1..b681eee 100644 (file)
@@ -21,6 +21,7 @@
 #include <StringConstants.h>
 #include "ocpayload.h"
 #include "ocrandom.h"
+#include "oic_string.h"
 
 namespace OC
 {
@@ -50,7 +51,7 @@ namespace OC
                     while(res)
                     {
                         char uuidString[UUID_STRING_SIZE];
-                        if(OCConvertUuidToString(res->sid, uuidString) != RAND_UUID_OK)
+                        if(OCConvertUuidToString(payload->sid, uuidString) != RAND_UUID_OK)
                         {
                             uuidString[0]= '\0';
                         }
@@ -81,19 +82,29 @@ namespace OC
                 {
                     while(colRes)
                     {
+                        // currently support for ipv4 is provided.
+                        OCDevAddr colAddr;
+                        colAddr.adapter = OC_ADAPTER_IP;
+                        colAddr.flags   = OC_IP_USE_V4;
+                        char *ptr = strtok(colRes->tags->baseURI, ":");
+                        OICStrcpy(colAddr.addr, sizeof(colAddr.addr), ptr);
+
                         if (colRes->tags->bitmap & OC_SECURE)
                         {
-                            m_devAddr.flags =
+                            colAddr.flags =
                                   (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
                         }
-
                         if (colRes->tags->port != 0)
                         {
-                             m_devAddr.port = colRes->tags->port;
+                             colAddr.port = colRes->tags->port;
+                        }
+                        else
+                        {
+                            colAddr.port = atoi(ptr+1);
                         }
 
                         m_resources.push_back(std::shared_ptr<OC::OCResource>(
-                                    new OC::OCResource(m_clientWrapper, m_devAddr,
+                                    new OC::OCResource(m_clientWrapper, colAddr,
                                         std::string(colRes->setLinks->href),
                                         std::string((char*)colRes->tags->di.id),
                                         (colRes->tags->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
index 4f1dd62..f441ca9 100644 (file)
@@ -123,6 +123,7 @@ namespace OC
 
         // first one is considered the root, everything else is considered a child of this one.
         OCRepresentation root = *it;
+        root.setDevAddr(clientResponse->devAddr);
         ++it;
 
         std::for_each(it, oc.representations().end(),
index 315f83b..2c91437 100644 (file)
@@ -37,6 +37,9 @@
 
 namespace OC
 {
+    static const char COAP[] = "coap://";
+    static const char COAPS[] = "coaps://";
+    static const char COAP_TCP[] = "coap+tcp://";
 
     void MessageContainer::setPayload(const OCPayload* rep)
     {
@@ -60,7 +63,6 @@ namespace OC
     void MessageContainer::setPayload(const OCDevicePayload* payload)
     {
         OCRepresentation rep;
-        rep.setUri(payload->uri);
         char uuidString[UUID_STRING_SIZE];
         if(payload->sid && RAND_UUID_OK == OCConvertUuidToString(payload->sid, uuidString))
         {
@@ -85,8 +87,6 @@ namespace OC
     void MessageContainer::setPayload(const OCPlatformPayload* payload)
     {
         OCRepresentation rep;
-        rep.setUri(payload->uri);
-
         rep[OC_RSRVD_PLATFORM_ID] = payload->info.platformID ?
             std::string(payload->info.platformID) :
             std::string();
@@ -641,6 +641,42 @@ namespace OC
     {
         m_children = children;
     }
+
+    void OCRepresentation::setDevAddr(const OCDevAddr m_devAddr)
+    {
+        std::ostringstream ss;
+        if (m_devAddr.flags & OC_SECURE)
+        {
+            ss << COAPS;
+        }
+        else if (m_devAddr.adapter & OC_ADAPTER_TCP)
+        {
+            ss << COAP_TCP;
+        }
+        else
+        {
+            ss << COAP;
+        }
+        if (m_devAddr.flags & OC_IP_USE_V6)
+        {
+            ss << '[' << m_devAddr.addr << ']';
+        }
+        else
+        {
+            ss << m_devAddr.addr;
+        }
+        if (m_devAddr.port)
+        {
+            ss << ':' << m_devAddr.port;
+        }
+        m_host = ss.str();
+    }
+
+    const std::string OCRepresentation::getHost() const
+    {
+        return m_host;
+    }
+
     void OCRepresentation::setUri(const char* uri)
     {
         m_uri = uri ? uri : "";
index 204b0da..2d11e46 100644 (file)
@@ -28,10 +28,7 @@ namespace OC {
 
 static const char COAP[] = "coap://";
 static const char COAPS[] = "coaps://";
-
-#ifdef TCP_ADAPTER
 static const char COAP_TCP[] = "coap+tcp://";
-#endif
 
 using OC::nil_guard;
 using OC::result_guard;
@@ -127,13 +124,11 @@ void OCResource::setHost(const std::string& host)
         prefix_len = sizeof(COAPS) - 1;
         m_devAddr.flags = static_cast<OCTransportFlags>(m_devAddr.flags & OC_SECURE);
     }
-#ifdef TCP_ADAPTER
     else if (host.compare(0, sizeof(COAP_TCP) - 1, COAP_TCP) == 0)
     {
         prefix_len = sizeof(COAP_TCP) - 1;
         m_devAddr.adapter = static_cast<OCTransportAdapter>(m_devAddr.adapter & OC_ADAPTER_TCP);
     }
-#endif
     else
     {
         throw ResourceInitException(m_uri.empty(), m_resourceTypes.empty(),
@@ -417,12 +412,10 @@ std::string OCResource::host() const
     {
         ss << COAPS;
     }
-#ifdef TCP_ADAPTER
     else if (m_devAddr.adapter & OC_ADAPTER_TCP)
     {
         ss << COAP_TCP;
     }
-#endif
     else
     {
         ss << COAP;
index df2f209..b3d92ca 100644 (file)
@@ -34,7 +34,7 @@ oclib_env = lib_env.Clone()
 oclib_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
-               '../csdk/ocrandom/include',
+               '../c_common/ocrandom/include',
                '../csdk/logger/include',
                '../oc_logger/include',
                '../csdk/connectivity/lib/libcoap-4.1.1'
index c254785..a638e4b 100644 (file)
@@ -41,10 +41,10 @@ if target_os == 'linux':
     # Build Common unit tests
        SConscript('c_common/oic_string/test/SConscript')
        SConscript('c_common/oic_malloc/test/SConscript')
+       SConscript('c_common/ocrandom/test/SConscript')
 
        # Build C unit tests
        SConscript('csdk/stack/test/SConscript')
-       SConscript('csdk/ocrandom/test/SConscript')
 
        SConscript('csdk/connectivity/test/SConscript')
 
index c679495..e1b0807 100644 (file)
@@ -47,8 +47,6 @@ namespace OC
 // CBOR->OCPayload and OCPayload->OCRepresentation conversions
 namespace OCRepresentationEncodingTest
 {
-
-    static const char uri1[] = "/testuri";
     static const uint8_t sid1[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
     static const char devicename1[] = "device name";
     static const char specver1[] = "spec version";
@@ -57,13 +55,11 @@ namespace OCRepresentationEncodingTest
     TEST(DeviceDiscoveryEncoding, Normal)
     {
         OCDevicePayload* device = OCDevicePayloadCreate(
-                uri1,
                 sid1,
                 devicename1,
                 specver1,
                 dmver1);
 
-        EXPECT_STREQ(uri1, device->uri);
         EXPECT_STREQ(devicename1, device->deviceName);
         EXPECT_STREQ(specver1, device->specVersion);
         EXPECT_STREQ(dmver1, device->dataModelVersion);
@@ -82,7 +78,6 @@ namespace OCRepresentationEncodingTest
                     cborData, cborSize));
         OICFree(cborData);
 
-        EXPECT_STREQ(device->uri, ((OCDevicePayload*)parsedDevice)->uri);
         EXPECT_STREQ(device->deviceName, ((OCDevicePayload*)parsedDevice)->deviceName);
         EXPECT_STREQ(device->specVersion, ((OCDevicePayload*)parsedDevice)->specVersion);
         EXPECT_STREQ(device->dataModelVersion, ((OCDevicePayload*)parsedDevice)->dataModelVersion);
@@ -94,15 +89,14 @@ namespace OCRepresentationEncodingTest
         mc.setPayload(parsedDevice);
         EXPECT_EQ(1u, mc.representations().size());
         const OC::OCRepresentation& r = mc.representations()[0];
-        EXPECT_STREQ(uri1, r.getUri().c_str());
         EXPECT_STREQ(devicename1, r.getValue<std::string>(OC_RSRVD_DEVICE_NAME).c_str());
         EXPECT_STREQ(specver1, r.getValue<std::string>(OC_RSRVD_SPEC_VERSION).c_str());
         EXPECT_STREQ(dmver1, r.getValue<std::string>(OC_RSRVD_DATA_MODEL_VERSION).c_str());
 
-
         OCPayloadDestroy(parsedDevice);
     }
 
+    static const char uri1[] = "/testuri";
     static char pfid1[] = "pfid";
     static char mfgnm1[] = "mfgnm";
     static char mfgurl1[] = "mfgurl";
@@ -120,9 +114,8 @@ namespace OCRepresentationEncodingTest
     {
         OCPlatformInfo info {pfid1, mfgnm1, mfgurl1, modelnum1, dom1, pfver1, osver1, hwver1,
             fwver1, url1, time1};
-        OCPlatformPayload* platform = OCPlatformPayloadCreate(uri1, &info);
+        OCPlatformPayload* platform = OCPlatformPayloadCreate(&info);
         EXPECT_EQ(PAYLOAD_TYPE_PLATFORM, ((OCPayload*)platform)->type);
-        EXPECT_STREQ(uri1, platform->uri);
         EXPECT_STREQ(pfid1, platform->info.platformID);
         EXPECT_STREQ(mfgnm1, platform->info.manufacturerName);
         EXPECT_STREQ(mfgurl1, platform->info.manufacturerUrl);
@@ -145,7 +138,6 @@ namespace OCRepresentationEncodingTest
 
         EXPECT_EQ(platform->base.type, ((OCPlatformPayload*)parsedPlatform)->base.type);
         OCPlatformPayload* platform2 = (OCPlatformPayload*)parsedPlatform;
-        EXPECT_STREQ(platform->uri, platform2->uri);
         EXPECT_STREQ(platform->info.platformID, platform2->info.platformID);
         EXPECT_STREQ(platform->info.manufacturerName, platform->info.manufacturerName);
         EXPECT_STREQ(platform->info.manufacturerUrl, platform->info.manufacturerUrl);
@@ -164,7 +156,6 @@ namespace OCRepresentationEncodingTest
         mc.setPayload(parsedPlatform);
         EXPECT_EQ(1u, mc.representations().size());
         const OC::OCRepresentation& r = mc.representations()[0];
-        EXPECT_STREQ(uri1, r.getUri().c_str());
         EXPECT_STREQ(pfid1, r.getValue<std::string>(OC_RSRVD_PLATFORM_ID).c_str());
         EXPECT_STREQ(mfgnm1, r.getValue<std::string>(OC_RSRVD_MFG_NAME).c_str());
         EXPECT_STREQ(mfgurl1, r.getValue<std::string>(OC_RSRVD_MFG_URL).c_str());
@@ -179,7 +170,30 @@ namespace OCRepresentationEncodingTest
 
         OCPayloadDestroy(parsedPlatform);
     }
+    TEST(PresencePayload, Normal)
+    {
+        uint32_t maxAge = 0;
+        uint32_t sequenceNumber = 0;
+        OCPresenceTrigger trigger = OC_PRESENCE_TRIGGER_CREATE;
+        OCPresencePayload *presence = OCPresencePayloadCreate(sequenceNumber, maxAge, trigger, uri1);
+
+        uint8_t* cborData;
+        size_t cborSize;
+        OCPayload* cparsed;
+        EXPECT_EQ(OC_STACK_OK, OCConvertPayload((OCPayload*)presence, &cborData, &cborSize));
+        EXPECT_EQ(OC_STACK_OK, OCParsePayload(&cparsed, PAYLOAD_TYPE_PRESENCE,
+                    cborData, cborSize));
+        OCPayloadDestroy((OCPayload*)presence);
+        OICFree(cborData);
 
+        OCPresencePayload* parsed = ((OCPresencePayload*)cparsed);
+        EXPECT_EQ(sequenceNumber, parsed->sequenceNumber);
+        EXPECT_EQ(maxAge, parsed->maxAge);
+        EXPECT_EQ(trigger, parsed->trigger);
+        EXPECT_STREQ(uri1, parsed->resourceType);
+
+        OCPayloadDestroy(cparsed);
+    }
     // Representation Payloads
     TEST(RepresentationEncoding, BaseAttributeTypes)
     {
@@ -633,12 +647,12 @@ namespace OCRepresentationEncodingTest
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+        payload->sid = (uint8_t*)OICMalloc(16);
         payload->resources = resource;
 
         OCResourcePayloadAddResourceType(resource, "rt.singleitem");
         OCResourcePayloadAddInterface(resource, "if.singleitem");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -666,13 +680,13 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, SingleItemFrontTrim)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
         OCResourcePayloadAddResourceType(resource, "    rt.singleitem");
         OCResourcePayloadAddInterface(resource, "    if.singleitem");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -699,13 +713,13 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, SingleItemBackTrim)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
         OCResourcePayloadAddResourceType(resource, "rt.singleitem    ");
         OCResourcePayloadAddInterface(resource, "if.singleitem    ");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -732,13 +746,13 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, SingleItemBothTrim)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
         OCResourcePayloadAddResourceType(resource, "    rt.singleitem    ");
         OCResourcePayloadAddInterface(resource, "    if.singleitem     ");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -765,6 +779,7 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemsNormal)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
@@ -773,7 +788,6 @@ namespace OCRepresentationEncodingTest
         OCResourcePayloadAddInterface(resource, "if.firstitem");
         OCResourcePayloadAddInterface(resource, "if.seconditem");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -802,6 +816,7 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemExtraLeadSpaces)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
@@ -810,7 +825,6 @@ namespace OCRepresentationEncodingTest
         OCResourcePayloadAddInterface(resource, "  if.firstitem");
         OCResourcePayloadAddInterface(resource, "  if.seconditem");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -839,6 +853,7 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemExtraTrailSpaces)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
@@ -847,7 +862,6 @@ namespace OCRepresentationEncodingTest
         OCResourcePayloadAddInterface(resource, "if.firstitem  ");
         OCResourcePayloadAddInterface(resource, "if.seconditem  ");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -876,6 +890,7 @@ namespace OCRepresentationEncodingTest
     TEST(DiscoveryRTandIF, MultiItemBothSpaces)
     {
         OCDiscoveryPayload* payload = OCDiscoveryPayloadCreate();
+        payload->sid = (uint8_t*)OICMalloc(16);
         OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
         payload->resources = resource;
 
@@ -884,7 +899,6 @@ namespace OCRepresentationEncodingTest
         OCResourcePayloadAddInterface(resource, "  if.firstitem  ");
         OCResourcePayloadAddInterface(resource, "  if.seconditem  ");
         resource->uri = OICStrdup("/uri/thing");
-        resource->sid = (uint8_t*)OICMalloc(16);
 
         uint8_t* cborData;
         size_t cborSize;
@@ -913,7 +927,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, SingleItemNormal)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "rt.firstitem");
         OCRepPayloadAddInterface(payload, "if.firstitem");
 
@@ -940,7 +953,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, SingleItemFrontTrim)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "  rt.firstitem");
         OCRepPayloadAddInterface(payload, "  if.firstitem");
 
@@ -967,7 +979,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, SingleItemBackTrim)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "rt.firstitem  ");
         OCRepPayloadAddInterface(payload, "if.firstitem  ");
 
@@ -994,7 +1005,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, SingleItemBothTrim)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "  rt.firstitem  ");
         OCRepPayloadAddInterface(payload, "  if.firstitem  ");
 
@@ -1021,7 +1031,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, MultiItemsNormal)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "rt.firstitem");
         OCRepPayloadAddResourceType(payload, "rt.seconditem");
         OCRepPayloadAddInterface(payload, "if.firstitem");
@@ -1052,7 +1061,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, MultiItemExtraLeadSpaces)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "  rt.firstitem");
         OCRepPayloadAddResourceType(payload, "  rt.seconditem");
         OCRepPayloadAddInterface(payload, "  if.firstitem");
@@ -1083,7 +1091,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, MultiItemExtraTrailSpaces)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "rt.firstitem  ");
         OCRepPayloadAddResourceType(payload, "rt.seconditem  ");
         OCRepPayloadAddInterface(payload, "if.firstitem  ");
@@ -1114,7 +1121,6 @@ namespace OCRepresentationEncodingTest
     TEST(RepresentationEncodingRTandIF, MultiItemExtraMiddleSpaces)
     {
         OCRepPayload* payload = OCRepPayloadCreate();
-        OCRepPayloadSetUri(payload, "/this/uri");
         OCRepPayloadAddResourceType(payload, "  rt.firstitem  ");
         OCRepPayloadAddResourceType(payload, "  rt.seconditem  ");
         OCRepPayloadAddInterface(payload, "  if.firstitem  ");
index befcdcb..5701fc2 100644 (file)
@@ -421,9 +421,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(nullptr, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -442,9 +442,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -463,9 +463,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         int badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<int>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -492,9 +492,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout);
 
         int badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<int>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -513,7 +513,7 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         (void)badout;
     }
 
@@ -535,9 +535,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource.getUri(), repout2.getUri());
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -556,9 +556,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -577,9 +577,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -598,9 +598,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -619,9 +619,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -640,9 +640,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -662,9 +662,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -683,9 +683,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -704,9 +704,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -726,9 +726,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -747,9 +747,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -768,9 +768,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -790,9 +790,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(repsource, repout2);
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -818,9 +818,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(inner2.getUri(), repout2[1].getUri());
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -860,9 +860,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(inner4.getUri(), repout2[1][1].getUri());
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
@@ -922,9 +922,9 @@ namespace OCRepresentationTest
         EXPECT_EQ(inner8.getUri(), repout2[1][1][1].getUri());
 
         double badout;
-        EXPECT_THROW(badout = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<double>(AttrName, badout));
         string badoutstr;
-        EXPECT_THROW(badoutstr = rep[AttrName], boost::bad_get);
+        EXPECT_FALSE(rep.getValue<string>(AttrName, badoutstr));
         (void)badout;
         (void)badoutstr;
     }
index 0506303..65b0921 100644 (file)
@@ -36,7 +36,7 @@ unittests_env.PrependUnique(CPPPATH = [
                '../csdk/connectivity/api',
                '../csdk/connectivity/external/inc',
                '../csdk/ocsocket/include',
-               '../csdk/ocrandom/include',
+               '../c_common/ocrandom/include',
                '../csdk/logger/include',
                '#extlibs/gtest/gtest-1.7.0/include',
                '#extlibs/hippomocks-master/HippoMocks',
index c35facf..e264962 100644 (file)
@@ -31,6 +31,8 @@ class BMISensorResource : public SoftSensorResource
 {
     public:
         BMISensorResource();
+        BMISensorResource(const BMISensorResource &other)=delete;
+        BMISensorResource& operator=( const BMISensorResource& rhs )=delete;
         ~BMISensorResource();
 
         virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
index b54622b..f322834 100644 (file)
@@ -25,7 +25,7 @@
 #include "BMISensorResource.h"
 
 
-BMISensorBundleActivator *bundle;
+BMISensorBundleActivator *g_bundleBMI;
 
 BMISensorBundleActivator::BMISensorBundleActivator()
 {
@@ -105,22 +105,22 @@ void BMISensorBundleActivator::destroyResource(BundleResource::Ptr resource)
 extern "C" void bmisensor_externalActivateBundle(ResourceContainerBundleAPI *resourceContainer,
         std::string bundleId)
 {
-    bundle = new BMISensorBundleActivator();
-    bundle->activateBundle(resourceContainer, bundleId);
+    g_bundleBMI = new BMISensorBundleActivator();
+    g_bundleBMI->activateBundle(resourceContainer, bundleId);
 }
 
 extern "C" void bmisensor_externalDeactivateBundle()
 {
-    bundle->deactivateBundle();
-    delete bundle;
+    g_bundleBMI->deactivateBundle();
+    delete g_bundleBMI;
 }
 
 extern "C" void bmisensor_externalCreateResource(resourceInfo resourceInfo)
 {
-    bundle->createResource(resourceInfo);
+    g_bundleBMI->createResource(resourceInfo);
 }
 
 extern "C" void bmisensor_externalDestroyResource(BundleResource::Ptr pBundleResource)
 {
-    bundle->destroyResource(pBundleResource);
+    g_bundleBMI->destroyResource(pBundleResource);
 }
index 5d029b9..e223629 100644 (file)
@@ -33,12 +33,11 @@ using OC::oc_log_stream;
 
 #define MAX_PATH 2048
 
-/* Annother way to create a context: */
+/* Another way to create a context: */
 auto info_logger = []() -> boost::iostreams::stream<OC::oc_log_stream> &
 {
     static OC::oc_log_stream ols(oc_make_ostream_logger);
     static boost::iostreams::stream<OC::oc_log_stream> os(ols);
-
     return os;
 };
 
index cc97d1d..e7ce3f3 100644 (file)
@@ -1,6 +1,6 @@
 //******************************************************************
 //
-// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+// Copyright 2015 Samsung Electronics All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //
@@ -18,8 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-// OCClient.cpp : Defines the entry point for the console application.
-//
+
 #include <string>
 #include <map>
 #include <cstdlib>
@@ -204,7 +203,7 @@ void postLightRepresentation(std::shared_ptr<OCResource> resource)
 
         std::cout << "Posting light representation..." << std::endl;
 
-        mylight.m_on_off = "false";
+        mylight.m_on_off = false;
 
         rep.setValue("on-off", mylight.m_on_off);
 
index 6780715..583094e 100644 (file)
@@ -32,6 +32,8 @@ class DiscomfortIndexSensorResource : public SoftSensorResource
     public:
         DiscomfortIndexSensorResource();
         ~DiscomfortIndexSensorResource();
+        DiscomfortIndexSensorResource(const DiscomfortIndexSensorResource &other)=delete;
+        DiscomfortIndexSensorResource& operator=( const DiscomfortIndexSensorResource& rhs )=delete;
 
         virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
 
index 147e3c4..27ac1cf 100644 (file)
@@ -24,7 +24,7 @@
 #include <sstream>
 #include "DiscomfortIndexSensorResource.h"
 
-DISensorBundleActivator *bundle;
+DISensorBundleActivator *g_bundleDI;
 
 DISensorBundleActivator::DISensorBundleActivator()
 {
@@ -106,22 +106,22 @@ void DISensorBundleActivator::destroyResource(BundleResource::Ptr resource)
 extern "C" void disensor_externalActivateBundle(ResourceContainerBundleAPI *resourceContainer,
         std::string bundleId)
 {
-    bundle = new DISensorBundleActivator();
-    bundle->activateBundle(resourceContainer, bundleId);
+    g_bundleDI = new DISensorBundleActivator();
+    g_bundleDI->activateBundle(resourceContainer, bundleId);
 }
 
 extern "C" void disensor_externalDeactivateBundle()
 {
-    bundle->deactivateBundle();
-    delete bundle;
+    g_bundleDI->deactivateBundle();
+    delete g_bundleDI;
 }
 
 extern "C" void disensor_externalCreateResource(resourceInfo resourceInfo)
 {
-    bundle->createResource(resourceInfo);
+    g_bundleDI->createResource(resourceInfo);
 }
 
 extern "C" void disensor_externalDestroyResource(BundleResource::Ptr pBundleResource)
 {
-    bundle->destroyResource(pBundleResource);
+    g_bundleDI->destroyResource(pBundleResource);
 }
index 903f6ba..36fad24 100644 (file)
@@ -26,7 +26,7 @@
 
 using namespace OIC::Service;
 
-HueSampleBundleActivator *bundle;
+HueSampleBundleActivator *g_bundleHUE;
 
 HueSampleBundleActivator::HueSampleBundleActivator()
 {
@@ -108,22 +108,22 @@ void HueSampleBundleActivator::destroyResource(BundleResource::Ptr pBundleResour
 extern "C" void huesample_externalActivateBundle(ResourceContainerBundleAPI *resourceContainer,
         std::string bundleId)
 {
-    bundle = new HueSampleBundleActivator();
-    bundle->activateBundle(resourceContainer, bundleId);
+    g_bundleHUE = new HueSampleBundleActivator();
+    g_bundleHUE->activateBundle(resourceContainer, bundleId);
 }
 
 extern "C" void huesample_externalDeactivateBundle()
 {
-    bundle->deactivateBundle();
-    delete bundle;
+    g_bundleHUE->deactivateBundle();
+    delete g_bundleHUE;
 }
 
 extern "C" void huesample_externalCreateResource(resourceInfo resourceInfo)
 {
-    bundle->createResource(resourceInfo);
+    g_bundleHUE->createResource(resourceInfo);
 }
 
 extern "C" void huesample_externalDestroyResource(BundleResource::Ptr pBundleResource)
 {
-    bundle->destroyResource(pBundleResource);
+    g_bundleHUE->destroyResource(pBundleResource);
 }
index f656f95..7bd6df1 100644 (file)
@@ -98,7 +98,6 @@
                                                                </option>
                                                                <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
                                                                        <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;C:\boost_1_56_0&quot;"/>
                                                                        <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\resource-encapsulation\src\resourceBroker\include&quot;"/>
                                                                        <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\resource-encapsulation\src\resourceCache\include&quot;"/>
                                                                        <listOptionValue builtIn="false" value="&quot;..\..\..\..\..\resource-encapsulation\src\common\utils\include&quot;"/>
index d4e6f42..d9c1130 100644 (file)
@@ -77,7 +77,7 @@ create_list_view(appdata_s *ad)
     // This button is set for devices which doesn't have H/W back key.
     btn = elm_button_add(nf);
     elm_object_style_set(btn, "naviframe/end_btn/default");
-    nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
+    nf_it = elm_naviframe_item_push(nf, "Container Client", btn, NULL, list, NULL);
     elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
 }
 
index b85eb44..6596a8e 100644 (file)
@@ -236,7 +236,7 @@ void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
     evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
     elm_object_part_content_set(layout, "log", log_entry);
 
-    nf_it = elm_naviframe_item_push(nf, "Resource Container", NULL, NULL, scroller, NULL);
+    nf_it = elm_naviframe_item_push(nf, "Container Client", NULL, NULL, scroller, NULL);
     elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
 
     // Show the UI list of group APIs
index 13e4714..6b50869 100644 (file)
@@ -98,7 +98,6 @@
                                                                </option>
                                                                <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
                                                                        <listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/inc}&quot;"/>
-                                                                       <listOptionValue builtIn="false" value="&quot;C:\boost_1_56_0&quot;"/>
                                                                        <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\resourceBroker\include&quot;"/>
                                                                        <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\resourceCache\include&quot;"/>
                                                                        <listOptionValue builtIn="false" value="&quot;..\..\..\..\src\common\utils\include&quot;"/>
index 5639986..31eb0cb 100644 (file)
@@ -27,8 +27,6 @@ using namespace std;
 
 void *showContainerAPIs(void *data);
 
-void containerCreateUI(void *data);
-
 static void startContainer(void *data, Evas_Object *obj, void *event_info);
 
 static void stopContainer(void *data, Evas_Object *obj, void *event_info);
index 22d080f..ea7886f 100644 (file)
@@ -43,6 +43,6 @@ using namespace OC;
 
 #define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.containerserver/res/ui_controls.edj"
 
-void containerCreateUI(void *data, Evas_Object *obj, void *event_info);
+void containerCreateUI(void *data);
 
 #endif // RCMAIN_H__
index 73e6cdd..eb5572b 100644 (file)
@@ -563,7 +563,7 @@ static void startContainer(void *data, Evas_Object *obj, void *event_info)
             s_containerFlag = true;
             s_hueBundleFlag = true;
             logMessage += "CONTAINER STARTED<br>";
-            logMessage += "ADD AND START BUNDLES<br>";
+            logMessage += "HUE BUNDLE STARTED<br>";
         }
         else
         {
@@ -625,13 +625,14 @@ naviframe_pop_cb(void *data, Elm_Object_Item *it)
         evas_object_del(listnew);
         listnew = NULL;
     }
+
+    ui_app_exit();
     return EINA_TRUE;
 }
 
 // Method to set up server screens
-void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
+void containerCreateUI(void *data)
 {
-       dlog_print(DLOG_INFO, LOG_TAG, "#### container UI");
     s_containerFlag = false;
     s_hueBundleFlag = false;
     Evas_Object *layout;
@@ -646,7 +647,6 @@ void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
     scroller = elm_scroller_add(nf);
     elm_scroller_bounce_set(scroller, EINA_FALSE, EINA_TRUE);
     elm_scroller_policy_set(scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
-    dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 1");
 
     // Layout
     layout = elm_layout_add(nf);
@@ -654,21 +654,18 @@ void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
     evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
 
     elm_object_content_set(scroller, layout);
-    dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 2");
 
     // Button
     start_button = elm_button_add(layout);
     elm_object_part_content_set(layout, "start_button", start_button);
     elm_object_text_set(start_button, "Start Container");
     evas_object_smart_callback_add(start_button, "clicked", startContainer, NULL);
-    dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 3");
 
     // Button
     stop_button = elm_button_add(layout);
     elm_object_part_content_set(layout, "stop_button", stop_button);
     elm_object_text_set(stop_button, "Stop Container");
     evas_object_smart_callback_add(stop_button, "clicked", stopContainer, NULL);
-    dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 4");
 
     // List
     listnew = elm_list_add(layout);
@@ -676,7 +673,6 @@ void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
     evas_object_smart_callback_add(listnew, "selected", list_selected_cb, NULL);
     elm_object_part_content_set(layout, "listnew", listnew);
     elm_list_go(listnew);
-    dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 5");
 
     // log_entry - text area for log
     log_entry = elm_entry_add(layout);
@@ -687,7 +683,6 @@ void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
     evas_object_size_hint_align_set(log_entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
     elm_object_part_content_set(layout, "log", log_entry);
 
-    nf_it = elm_naviframe_item_push(nf, "Resource Container", NULL, NULL, scroller, NULL);
+    nf_it = elm_naviframe_item_push(nf, "Container Server", NULL, NULL, scroller, NULL);
     elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
-    dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 6");
 }
index c845270..330a42f 100644 (file)
@@ -65,16 +65,15 @@ create_list_view(appdata_s *ad)
     elm_list_mode_set(list, ELM_LIST_COMPRESS);
     evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
 
-    // Main Menu Items Here
-    elm_list_item_append(list, "Resource Container", NULL, NULL, containerCreateUI, nf);
-
     elm_list_go(list);
 
     // This button is set for devices which doesn't have H/W back key.
     btn = elm_button_add(nf);
     elm_object_style_set(btn, "naviframe/end_btn/default");
-    nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
+    nf_it = elm_naviframe_item_push(nf, "Container Server", btn, NULL, list, NULL);
     elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
+
+    containerCreateUI(nf);
 }
 
 
index 227c1a7..b6635ed 100644 (file)
@@ -60,6 +60,8 @@ namespace OIC
                 typedef RemoteResourceUnit::UPDATE_MSG REMOTE_MSG;
 
                 DiscoverResourceUnit(const std::string &bundleId);
+                DiscoverResourceUnit(const DiscoverResourceUnit &other)=delete;
+                DiscoverResourceUnit& operator=( const DiscoverResourceUnit& rhs )=delete;
                 ~DiscoverResourceUnit();
 
                 void startDiscover(DiscoverResourceInfo info, UpdatedCB updatedCB);
index 5f80354..1d0ba5a 100644 (file)
@@ -24,6 +24,7 @@
 
 #include "payload_logging.h"
 #include "oic_malloc.h"
+#include "octypes.h"
 
 #include "rdpayload.h"
 
@@ -46,7 +47,7 @@ static void printStoragedResources(OCRDStorePublishResources *payload)
     }
 }
 
-OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload)
+OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload, const OCDevAddr *address)
 {
     OCResourceCollectionPayload *storeResource = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
     if (!storeResource)
@@ -55,11 +56,14 @@ OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *pay
         return OC_STACK_NO_MEMORY;
     }
 
-    OC_LOG(DEBUG, TAG, "Storing Resources ... ");
+    OC_LOG_V(DEBUG, TAG, "Storing Resources for %s:%u", address->addr, address->port);
+
+    char rdPubAddr[MAX_ADDR_STR_SIZE];
+    snprintf(rdPubAddr, MAX_ADDR_STR_SIZE, "%s:%d", address->addr, address->port);
 
     OCTagsPayload *tags = payload->tags;
-    storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, tags->baseURI,
-        tags->bitmap, tags->port, tags->ins, tags->rts, tags->drel, tags->ttl);
+    storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, rdPubAddr,
+        tags->bitmap, address->port, tags->ins, tags->rts, tags->drel, tags->ttl);
     if (!storeResource->tags)
     {
         OC_LOG(ERROR, TAG, "Failed allocating memory for tags.");
index bbc5e48..aefdb46 100644 (file)
@@ -35,10 +35,11 @@ typedef struct OCRDStorePublishResources
  * Stores the publish resources.
  *
  * @param payload RDPublish payload sent from the remote device.
+ * @param address The address of the device publishing resources.
  *
  * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR in case of error.
  */
-OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload);
+OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload, const OCDevAddr *address);
 
 #ifdef __cplusplus
 }
index 6b90b86..d8bbfa6 100644 (file)
@@ -330,6 +330,9 @@ OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
         goto no_memory;
     }
 
+    OCTagsLog(DEBUG, rdPayload->rdPublish->tags);
+    OCLinksLog(DEBUG, rdPayload->rdPublish->setLinks);
+
     OCDevAddr rdAddr = { 0 };
     OICStrcpy(rdAddr.addr, MAX_ADDR_STR_SIZE, addr);
     rdAddr.port = port;
index 4b67b97..7713679 100644 (file)
@@ -97,7 +97,7 @@ static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *
     OCRDPayload *payload = (OCRDPayload *)ehRequest->payload;
     if (payload && payload->rdPublish)
     {
-        OCRDStorePublishedResources(payload->rdPublish);
+        OCRDStorePublishedResources(payload->rdPublish, &ehRequest->devAddr);
     }
 
     OCRDPayload *rdPayload = OCRDPayloadCreate();
index f38d309..4354032 100644 (file)
@@ -540,8 +540,15 @@ Java_org_iotivity_service_server_RcsResourceObject_nativeSetGetRequestHandler
     auto res = getResource(env, obj);
     VERIFY_NO_EXC(env);
 
-    res->setGetRequestHandler(std::bind(onGetRequest, std::placeholders::_1, std::placeholders::_2,
-            JavaGlobalRef{ env, listenerObj }));
+    if (listenerObj)
+    {
+        res->setGetRequestHandler(std::bind(onGetRequest, std::placeholders::_1, std::placeholders::_2,
+                JavaGlobalRef{ env, listenerObj }));
+    }
+    else
+    {
+        res->setGetRequestHandler({ });
+    }
 }
 
 JNIEXPORT void JNICALL
@@ -553,8 +560,15 @@ Java_org_iotivity_service_server_RcsResourceObject_nativeSetSetRequestHandler
     auto res = getResource(env, obj);
     VERIFY_NO_EXC(env);
 
-    res->setSetRequestHandler(std::bind(onSetRequest, std::placeholders::_1, std::placeholders::_2,
-           JavaGlobalRef{ env, listenerObj }));
+    if (listenerObj)
+    {
+        res->setSetRequestHandler(std::bind(onSetRequest, std::placeholders::_1,
+                std::placeholders::_2, JavaGlobalRef{ env, listenerObj }));
+    }
+    else
+    {
+        res->setSetRequestHandler({ });
+    }
 }
 
 JNIEXPORT void JNICALL
old mode 100755 (executable)
new mode 100644 (file)
index 68c6f66..98d7076
@@ -393,7 +393,7 @@ bool selectResourceType(std::string& resourceType)
         return true;
     case REQUEST_LIGHT:
         resourceType = LIGHT;
-        defaultKey = "Light";
+        defaultKey = "Brightness";
         return true;
     default :
         std::cout << "Invalid input, please try again" << std::endl;
index c8734dc..5177093 100644 (file)
 #ifndef RECLIENT_H__
 #define RECLIENT_H__
 
+#include <string>
+
 typedef void(*ClientMenuHandler)();
 typedef int ReturnValue;
 
+const std::string TEMPERATURE_URI = "/a/TempSensor";
+const std::string LIGHT_URI = "/a/light";
+const std::string TEMPERATURE_RT = "oic.r.temperaturesensor";
+const std::string LIGHT_RT = "oic.r.light";
+const std::string TEMPERATURE_AK = "Temperature";
+const std::string LIGHT_AK = "Brightness";
+
+void client_cb(void *data);
+
 void *showClientAPIs(void *data);
 
 #endif // RECLIENT_H__
\ No newline at end of file
index 0c947a0..55bd6ce 100644 (file)
@@ -43,6 +43,8 @@ using namespace OC;
 
 #define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.resampleclient/res/ui_controls.edj"
 
-void client_cb(void *data, Evas_Object *obj, void *event_info);
+void discoverTempSensor(void *data, Evas_Object *obj, void *event_info);
+
+void discoverLight(void *data, Evas_Object *obj, void *event_info);
 
 #endif // RECLIENTMAIN_H__
\ No newline at end of file
index d01f195..8761e1d 100644 (file)
 #include<iostream>
 
 #include "reclientmain.h"
-
 #include "RCSDiscoveryManager.h"
 #include "RCSRemoteResourceObject.h"
 #include "RCSResourceAttributes.h"
 #include "RCSAddress.h"
-
 #include "OCPlatform.h"
 
 # define checkResource nullptr == resource?false:true
@@ -37,16 +35,13 @@ using namespace std;
 using namespace OC;
 using namespace OIC::Service;
 
-constexpr int CORRECT_INPUT = 1;
-constexpr int INCORRECT_INPUT = 2;
-constexpr int QUIT_INPUT = 3;
-
 std::shared_ptr<RCSRemoteResourceObject>  resource;
 std::vector<RCSRemoteResourceObject::Ptr> resourceList;
 std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
 
-const std::string defaultKey = "Temperature";
-const std::string resourceType = "oic.r.temperaturesensor";
+std::string g_resourceUri;
+std::string g_resourceType;
+std::string g_attributeKey;
 
 static Evas_Object *log_entry = NULL;
 static Evas_Object *list = NULL;
@@ -93,7 +88,7 @@ void onResourceDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource
 
     resourceList.push_back(foundResource);
 
-    if ("/a/TempSensor" == resourceURI)
+    if (g_resourceUri == resourceURI)
         resource = foundResource;
 }
 
@@ -260,13 +255,12 @@ static void getAttributeFromRemoteServer(void *data, Evas_Object *obj, void *eve
     }
 }
 
-static void setAttributeToRemoteServer(int setTemperature)
+static void setAttributeToRemoteServer(int setValue)
 {
-    string key = "Temperature";
     string logMessage = "";
 
     RCSResourceAttributes setAttribute;
-    setAttribute[key] = setTemperature;
+    setAttribute[g_attributeKey] = setValue;
 
     if (checkResource)
     {
@@ -421,8 +415,8 @@ static void getCachedAttribute(void *data, Evas_Object *obj, void *event_info)
     {
         try
         {
-            logMessage = logMessage + "KEY:" + defaultKey.c_str() + "<br>";
-            int attrValue = resource->getCachedAttribute(defaultKey).get< int >();
+            logMessage = logMessage + "KEY:" + g_attributeKey.c_str() + "<br>";
+            int attrValue = resource->getCachedAttribute(g_attributeKey).get< int >();
             logMessage = logMessage + "VALUE:" + to_string(attrValue) + "<br>";
         }
         catch (const RCSBadRequestException &e)
@@ -478,10 +472,12 @@ void discoverResource()
 
     while (!discoveryTask)
     {
+        resourceList.clear();
+        resource = nullptr;
         try
         {
             discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
-                                RCSAddress::multicast(), resourceType, &onResourceDiscovered);
+                                RCSAddress::multicast(), g_resourceType, &onResourceDiscovered);
         }
         catch (const RCSPlatformException &e)
         {
@@ -504,6 +500,7 @@ void cancelDiscoverResource()
     else
     {
         discoveryTask->cancel();
+        discoveryTask = nullptr;
 
         logMessage += "Discovery canceled <br>";
 
@@ -538,31 +535,31 @@ popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
 {
     temperature_popup_fields *popup_fields = (temperature_popup_fields *)data;
     Evas_Object *entry = popup_fields->entry;
-    const char *temperatureString = elm_entry_entry_get(entry);
+    const char *attributeString = elm_entry_entry_get(entry);
     // Remove white spaces(if any) at the beginning
     int beginning = 0;
-    while (temperatureString[beginning] == ' ')
+    while (attributeString[beginning] == ' ')
     {
         (beginning)++;
     }
 
-    int len = strlen(temperatureString);
-    if (NULL == temperatureString || 1 > len)
+    int len = strlen(attributeString);
+    if (NULL == attributeString || 1 > len)
     {
-        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL Temperature Value");
-        string logMessage = "Temperature Cannot be NULL<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL attribute Value");
+        string logMessage = g_attributeKey + " Cannot be NULL<br>";
         logMessage += "----------------------<br>";
         dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
         ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog, &logMessage);
     }
     else
     {
-        int temperate = atoi(temperatureString);
-        string tempString(temperatureString);
-        setAttributeToRemoteServer(temperate);
-        dlog_print(DLOG_INFO, LOG_TAG, "#### Temperature to set : %d", temperate);
+        int attributeValue = atoi(attributeString);
+        string attrString(attributeString);
+        setAttributeToRemoteServer(attributeValue);
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Attribute to set : %d", attributeValue);
 
-        string logMessage = "Temperature to set : " + tempString + "<br>";
+        string logMessage = g_attributeKey + " to set : " + attrString + "<br>";
         logMessage += "----------------------<br>";
         dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
         ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
@@ -573,7 +570,7 @@ popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
 }
 
 static void
-list_scheduled_actionset_cb(void *data, Evas_Object *obj, void *event_info)
+list_get_attribute_value_cb(void *data, Evas_Object *obj, void *event_info)
 {
     Evas_Object *popup, *btn;
     Evas_Object *nf = naviframe;
@@ -585,7 +582,14 @@ list_scheduled_actionset_cb(void *data, Evas_Object *obj, void *event_info)
     elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
     eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
     evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
-    elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+    if (LIGHT_RT == g_resourceType)
+    {
+        elm_object_part_text_set(popup, "title,text", "Enter the brightness");
+    }
+    else
+    {
+        elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+    }
 
     layout = elm_layout_add(popup);
     elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_datetime_text");
@@ -598,7 +602,14 @@ list_scheduled_actionset_cb(void *data, Evas_Object *obj, void *event_info)
     evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
     evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
     eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
-    elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+    if (LIGHT_RT == g_resourceType)
+    {
+        elm_object_part_text_set(entry, "elm.guide", "RANGE (0 - 50)");
+    }
+    else
+    {
+        elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+    }
     elm_entry_input_panel_layout_set(entry, ELM_INPUT_PANEL_LAYOUT_NUMBER);
     elm_object_part_content_set(layout, "elm.swallow.content", entry);
 
@@ -676,7 +687,7 @@ void *showClientAPIs(void *data)
                              getAttributeFromRemoteServer, NULL);
 
         elm_list_item_append(list, "4. Set Attribute", NULL, NULL,
-                             list_scheduled_actionset_cb, NULL);
+                             list_get_attribute_value_cb, NULL);
 
         elm_list_item_append(list, "5. Start Caching - No update", NULL, NULL,
                              startCachingWithoutCallback, NULL);
@@ -716,8 +727,7 @@ naviframe_pop_cb(void *data, Elm_Object_Item *it)
     return EINA_TRUE;
 }
 
-// Method to be called when the Group APIs UI Button is selected
-void client_cb(void *data, Evas_Object *obj, void *event_info)
+void client_cb(void *data)
 {
     Evas_Object *layout;
     Evas_Object *scroller;
@@ -771,3 +781,21 @@ void client_cb(void *data, Evas_Object *obj, void *event_info)
     nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", NULL, NULL, scroller, NULL);
     elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
 }
+
+void discoverTempSensor(void *data, Evas_Object *obj, void *event_info)
+{
+    g_resourceUri = TEMPERATURE_URI;
+    g_resourceType = TEMPERATURE_RT;
+    g_attributeKey = TEMPERATURE_AK;
+
+    client_cb(data);
+}
+
+void discoverLight(void *data, Evas_Object *obj, void *event_info)
+{
+    g_resourceUri = LIGHT_URI;
+    g_resourceType = LIGHT_RT;
+    g_attributeKey = LIGHT_AK;
+
+    client_cb(data);
+}
index dfbbbf5..4e53fad 100644 (file)
@@ -69,6 +69,11 @@ create_list_view(appdata_s *ad)
     evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
 
     // Main Menu Items Here
+    elm_list_item_append(list, "Discover Temperature Sensor Resource", NULL, NULL, discoverTempSensor,
+                         nf);
+
+    elm_list_item_append(list, "Discover Light Resource", NULL, NULL, discoverLight, nf);
+
     elm_list_go(list);
 
     // This button is set for devices which doesn't have H/W back key.
@@ -76,8 +81,6 @@ create_list_view(appdata_s *ad)
     elm_object_style_set(btn, "naviframe/end_btn/default");
     nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
     elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
-
-    client_cb(nf, NULL, NULL);
 }
 
 
index 1e5a899..99b5784 100644 (file)
@@ -35,7 +35,7 @@ using namespace OC;
 #ifdef  LOG_TAG
 #undef  LOG_TAG
 #endif
-#define LOG_TAG "reservermain"
+#define LOG_TAG "reserver"
 
 #if !defined(PACKAGE)
 #define PACKAGE "org.tizen.resampleserver"
@@ -43,6 +43,8 @@ using namespace OC;
 
 #define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.resampleserver/res/ui_controls.edj"
 
-void serverCreateUI(void *data, Evas_Object *obj, void *event_info);
+void temperatureResource(void *data, Evas_Object *obj, void *event_info);
+
+void lightResource(void *data, Evas_Object *obj, void *event_info);
 
 #endif // REMAIN_H__
\ No newline at end of file
index a8386d1..8aed849 100644 (file)
@@ -36,11 +36,13 @@ constexpr int DEFALUT_VALUE = 0;
 constexpr int PRESENCE_ON = 1;
 constexpr int PRESENCE_OFF = 2;
 
-std::string resourceUri = "/a/TempSensor";
-std::string resourceType = "oic.r.temperaturesensor";
-std::string resourceInterface = "oic.if.";
-std::string attributeKey = "Temperature";
-int isPresenceOn = PRESENCE_ON;
+const std::string TEMPERATURE_URI = "/a/TempSensor";
+const std::string LIGHT_URI = "/a/light";
+const std::string TEMPERATURE_RT = "oic.r.temperaturesensor";
+const std::string LIGHT_RT = "oic.r.light";
+const std::string TEMPERATURE_AK = "Temperature";
+const std::string LIGHT_AK = "Brightness";
+const std::string RESOURCE_INTERFACE = "oic.if.";
 
 enum class Control
 {
@@ -54,6 +56,6 @@ void start_server(void *data, Evas_Object *obj, void *event_info);
 
 void start_server_cb(void *data, Evas_Object *obj, void *event_info);
 
-void *showGroupAPIs(void *data);
+void *showAPIs(void *data);
 
 #endif // RESERVER_H__
\ No newline at end of file
index 849734a..57fb281 100644 (file)
@@ -66,7 +66,10 @@ create_list_view(appdata_s *ad)
     evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
 
     // Main Menu Items Here
-    elm_list_item_append(list, "Start Temperature Sensor", NULL, NULL, serverCreateUI, nf);
+    elm_list_item_append(list, "Start Temperature Sensor Resource", NULL, NULL, temperatureResource,
+                         nf);
+
+    elm_list_item_append(list, "Start Light Resource", NULL, NULL, lightResource, nf);
 
     elm_list_go(list);
 
index 6f837c5..4e74617 100644 (file)
@@ -30,10 +30,16 @@ using namespace std;
 using namespace OC;
 using namespace OIC::Service;
 
+# define checkServer NULL!=server?true:false
+
 RCSResourceObject::Ptr server;
+static bool serverStarted = false;
 static bool serverCallback = false;
+int isPresenceOn = PRESENCE_ON;
 
-# define checkServer NULL!=server?true:false
+std::string g_resourceUri;
+std::string g_resourceType;
+std::string g_attributeKey;
 
 static Evas_Object *log_entry = NULL;
 static Evas_Object *list = NULL;
@@ -70,17 +76,18 @@ void printAttribute(const RCSResourceAttributes &attrs)
 
 static void onDestroy()
 {
-    server = NULL;
     string logMessage = "SERVER DESTROYED";
 
-    if(isPresenceOn == PRESENCE_ON)
+    if(true == serverStarted)
     {
-        OCPlatform::stopPresence();
-    }
+        server = nullptr;
+        if(isPresenceOn == PRESENCE_ON)
+        {
+            OCPlatform::stopPresence();
+        }
 
-    dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
-    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
-                                          &logMessage);
+        serverStarted = false;
+    }
 }
 
 //hander for get request (if developer choose second option for resource Creation)
@@ -129,16 +136,16 @@ static void list_selected_cb(void *data, Evas_Object *obj, void *event_info)
     elm_list_item_selected_set(it, EINA_FALSE);
 }
 
-static void increaseTemp(void *data, Evas_Object *obj, void *event_info)
+static void increaseAttribute(void *data, Evas_Object *obj, void *event_info)
 {
     string logMessage = "";
 
     if (checkServer)
     {
         RCSResourceObject::LockGuard lock(server);
-        server->getAttributes()[attributeKey] = server->getAttribute<int>(attributeKey) + 10;
-        string tempString  = std::to_string(server->getAttribute<int>(attributeKey));
-        logMessage = "TEMPERATURE CHANGED : " + tempString + "<br>";
+        server->getAttributes()[g_attributeKey] = server->getAttribute<int>(g_attributeKey) + 1;
+        string tempString  = std::to_string(server->getAttribute<int>(g_attributeKey));
+        logMessage = g_attributeKey + " CHANGED : " + tempString + "<br>";
 
     }
     else
@@ -152,16 +159,16 @@ static void increaseTemp(void *data, Evas_Object *obj, void *event_info)
                                           &logMessage);
 }
 
-static void decreaseTemp(void *data, Evas_Object *obj, void *event_info)
+static void decreaseAttribute(void *data, Evas_Object *obj, void *event_info)
 {
     string logMessage = "";
 
     if (checkServer)
     {
         RCSResourceObject::LockGuard lock(server);
-        server->getAttributes()[attributeKey] = server->getAttribute<int>(attributeKey) - 10;
-        string tempString  = std::to_string(server->getAttribute<int>(attributeKey));
-        logMessage = "TEMPERATURE CHANGED : " + tempString + "<br>";
+        server->getAttributes()[g_attributeKey] = server->getAttribute<int>(g_attributeKey) - 1;
+        string tempString  = std::to_string(server->getAttribute<int>(g_attributeKey));
+        logMessage = g_attributeKey + " CHANGED : " + tempString + "<br>";
     }
     else
     {
@@ -180,8 +187,8 @@ static void initServer()
 
     try
     {
-        server = RCSResourceObject::Builder(resourceUri, resourceType,
-                                            resourceInterface).setDiscoverable(true).setObservable(true).build();
+        server = RCSResourceObject::Builder(g_resourceUri, g_resourceType,
+                                            RESOURCE_INTERFACE).setDiscoverable(true).setObservable(true).build();
     }
     catch (const RCSPlatformException &e)
     {
@@ -190,14 +197,14 @@ static void initServer()
 
     server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
     server->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
-    server->setAttribute(attributeKey, DEFALUT_VALUE);
+    server->setAttribute(g_attributeKey, DEFALUT_VALUE);
 
     string logMessage = "SERVER CREATED<br>";
     dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
     ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
                                           &logMessage);
 
-    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showGroupAPIs, NULL);
+    ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showAPIs, NULL);
 }
 
 static void
@@ -213,30 +220,30 @@ popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
 {
     datetime_popup_fields *popup_fields = (datetime_popup_fields *)data;
     Evas_Object *entry = popup_fields->entry;
-    const char *temperatureString = elm_entry_entry_get(entry);
+    const char *attributeString = elm_entry_entry_get(entry);
     // Remove white spaces(if any) at the beginning
     string logMessage = "";
     int beginning = 0;
-    while (temperatureString[beginning] == ' ')
+    while (attributeString[beginning] == ' ')
     {
         (beginning)++;
     }
 
-    int len = strlen(temperatureString);
-    if (NULL == temperatureString || 1 > len)
+    int len = strlen(attributeString);
+    if (NULL == attributeString || 1 > len)
     {
-        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL Temperature Value");
-        logMessage = "Temperature Cannot be NULL<br>";
+        dlog_print(DLOG_INFO, LOG_TAG, "#### Read NULL Value");
+        logMessage = g_attributeKey + "Cannot be NULL<br>";
     }
     else
     {
         if (checkServer)
         {
             RCSResourceObject::LockGuard lock(server);
-            int temperate = atoi(temperatureString);
-            server->getAttributes()[attributeKey] = temperate;
-            logMessage = "TEMPERATURE CHANGED : " + to_string(server->getAttribute<int>
-                         (attributeKey)) + "<br>";
+            int attributeInt = atoi(attributeString);
+            server->getAttributes()[g_attributeKey] = attributeInt;
+            logMessage = g_attributeKey + " CHANGED : " + to_string(server->getAttribute<int>
+                         (g_attributeKey)) + "<br>";
         }
         else
         {
@@ -253,7 +260,7 @@ popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
 }
 
 static void
-list_get_temperaure_cb(void *data, Evas_Object *obj, void *event_info)
+list_get_attribute_cb(void *data, Evas_Object *obj, void *event_info)
 {
     Evas_Object *popup, *btn;
     Evas_Object *nf = naviframe;
@@ -265,7 +272,14 @@ list_get_temperaure_cb(void *data, Evas_Object *obj, void *event_info)
     elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
     eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
     evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
-    elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+    if (LIGHT_RT == g_resourceType)
+    {
+        elm_object_part_text_set(popup, "title,text", "Enter the brightness");
+    }
+    else
+    {
+        elm_object_part_text_set(popup, "title,text", "Enter the temperature");
+    }
 
     layout = elm_layout_add(popup);
     elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_datetime_text");
@@ -278,7 +292,15 @@ list_get_temperaure_cb(void *data, Evas_Object *obj, void *event_info)
     evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
     evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
     eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
-    elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+    if (LIGHT_RT == g_resourceType)
+    {
+        elm_object_part_text_set(entry, "elm.guide", "RANGE (0 - 50)");
+    }
+    else
+    {
+        elm_object_part_text_set(entry, "elm.guide", "in degree celsius");
+    }
+
     elm_entry_input_panel_layout_set(entry, ELM_INPUT_PANEL_LAYOUT_NUMBER);
     elm_object_part_content_set(layout, "elm.swallow.content", entry);
 
@@ -311,21 +333,36 @@ list_get_temperaure_cb(void *data, Evas_Object *obj, void *event_info)
     evas_object_show(popup);
 }
 
-void *showGroupAPIs(void *data)
+void *showAPIs(void *data)
 {
     // Add items to the list only if the list is empty
     const Eina_List *eina_list = elm_list_items_get(list);
     int count = eina_list_count(eina_list);
     if (!count)
     {
-        elm_list_item_append(list, "1. Increase Temperature", NULL, NULL,
-                             increaseTemp, NULL);
+        if (LIGHT_RT == g_resourceType)
+        {
+            elm_list_item_append(list, "1. Increase Brightness", NULL, NULL,
+                                 increaseAttribute, NULL);
+
+            elm_list_item_append(list, "2. Decrease Brightness", NULL, NULL,
+                                 decreaseAttribute, NULL);
 
-        elm_list_item_append(list, "2. Decrease Temperature", NULL, NULL,
-                             decreaseTemp, NULL);
+            elm_list_item_append(list, "3. Set Brightness", NULL, NULL,
+                                 list_get_attribute_cb, NULL);
+        }
+        else
+        {
+            elm_list_item_append(list, "1. Increase Temperature", NULL, NULL,
+                                 increaseAttribute, NULL);
+
+            elm_list_item_append(list, "2. Decrease Temperature", NULL, NULL,
+                                 decreaseAttribute, NULL);
+
+            elm_list_item_append(list, "3. Set Temperature", NULL, NULL,
+                                 list_get_attribute_cb, NULL);
+        }
 
-        elm_list_item_append(list, "3. Set Temperature", NULL, NULL,
-                             list_get_temperaure_cb, NULL);
 
         elm_list_go(list);
     }
@@ -408,6 +445,7 @@ void serverCreateUI(void *data, Evas_Object *obj, void *event_info)
 void start_server(void *data, Evas_Object *obj, void *event_info)
 {
     server = NULL;
+    serverStarted = true;
     string logMessage = "SERVER WITHOUT CALLBACK<br>";
 
     serverCallback = false;
@@ -421,6 +459,7 @@ void start_server(void *data, Evas_Object *obj, void *event_info)
 void start_server_cb(void *data, Evas_Object *obj, void *event_info)
 {
     server = NULL;
+    serverStarted = true;
     string logMessage = "SERVER WITH CALLBACK<br>";
 
     serverCallback = true;
@@ -442,3 +481,21 @@ void start_server_cb(void *data, Evas_Object *obj, void *event_info)
                                           &logMessage);
 
 }
+
+void temperatureResource(void *data, Evas_Object *obj, void *event_info)
+{
+    g_resourceUri = TEMPERATURE_URI;
+    g_resourceType = TEMPERATURE_RT;
+    g_attributeKey = TEMPERATURE_AK;
+
+    serverCreateUI(data, NULL, NULL);
+}
+
+void lightResource(void *data, Evas_Object *obj, void *event_info)
+{
+    g_resourceUri = LIGHT_URI;
+    g_resourceType = LIGHT_RT;
+    g_attributeKey = LIGHT_AK;
+
+    serverCreateUI(data, NULL, NULL);
+}
index 7b36f4f..9744e49 100644 (file)
@@ -53,6 +53,9 @@ namespace OIC
             typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
                     SetCallback;
 
+            typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int)>
+                    PutCallback;
+
             typedef std::function<void(const HeaderOptions&, const ResponseStatement&, int, int)>
                     ObserveCallback;
 
@@ -63,6 +66,7 @@ namespace OIC
 
             virtual void requestGet(GetCallback) = 0;
             virtual void requestSet(const RCSResourceAttributes&, SetCallback) = 0;
+            virtual void requestPut(const RCSResourceAttributes&, PutCallback) = 0;
             virtual void requestObserve(ObserveCallback) = 0;
             virtual void cancelObserve() = 0;
 
index fb22426..a78d7b8 100644 (file)
@@ -107,6 +107,21 @@ namespace OIC
             {
                 using namespace std::placeholders;
 
+                typedef OCStackResult(BaseResource::*PostFunc)(
+                        const OC::OCRepresentation&,
+                        const OC::QueryParamsMap&, OC::PostCallback);
+
+                invokeOC(m_baseResource, static_cast< PostFunc >(&BaseResource::post),
+                        ResourceAttributesConverter::toOCRepresentation(attrs),
+                        OC::QueryParamsMap{ },
+                        std::bind(safeCallback< SetCallback >, WeakFromThis(),
+                                std::move(callback), _1, _2, _3));
+            }
+
+            void requestPut(const RCSResourceAttributes& attrs, PutCallback callback)
+            {
+                using namespace std::placeholders;
+
                 typedef OCStackResult(BaseResource::*PutFunc)(
                         const OC::OCRepresentation&,
                         const OC::QueryParamsMap&, OC::PutCallback);
@@ -114,7 +129,7 @@ namespace OIC
                 invokeOC(m_baseResource, static_cast< PutFunc >(&BaseResource::put),
                         ResourceAttributesConverter::toOCRepresentation(attrs),
                         OC::QueryParamsMap{ },
-                        std::bind(safeCallback< SetCallback >, WeakFromThis(),
+                        std::bind(safeCallback< PutCallback >, WeakFromThis(),
                                 std::move(callback), _1, _2, _3));
             }
 
@@ -128,7 +143,7 @@ namespace OIC
                 invokeOC(m_baseResource, static_cast< ObserveFunc >(&BaseResource::observe),
                         OC::ObserveType::ObserveAll, OC::QueryParamsMap{ },
                         std::bind(safeObserveCallback, WeakFromThis(),
-                                                       std::move(callback), _1, _2, _3, _4));
+                                std::move(callback), _1, _2, _3, _4));
             }
 
             void cancelObserve()
index 6355fa5..15e8230 100644 (file)
@@ -40,6 +40,9 @@ public:
     virtual OCStackResult put(
             const OC::OCRepresentation&, const OC::QueryParamsMap&, OC::PutCallback) = 0;
 
+    virtual OCStackResult post(
+            const OC::OCRepresentation&, const OC::QueryParamsMap&, OC::PostCallback) = 0;
+
     virtual OCStackResult observe(
             OC::ObserveType, const OC::QueryParamsMap&, OC::ObserveCallback) = 0;
 
index 575cb2b..97ba03b 100644 (file)
@@ -466,7 +466,7 @@ namespace OIC
                 return handleRequestGet(request);
             }
 
-            if (request->getRequestType() == "PUT")
+            if (request->getRequestType() == "POST")
             {
                 return handleRequestSet(request);
             }
old mode 100755 (executable)
new mode 100644 (file)
index 260cb0b..efcb2a7
@@ -40,7 +40,7 @@ simulator_env.AppendUnique(CPPPATH = ['inc', 'src/client-controller', 'src/servi
 simulator_env.AppendUnique(CPPPATH = [
                '../../resource/include/',
                '../../resource/csdk/stack/include',
-               '../../resource/csdk/ocrandom/include',
+               '../../resource/c_common/ocrandom/include',
                '../../resource/csdk/logger/include',
                '../../resource/oc_logger/include',
                './ramlparser/raml',
index 28512a8..3cb3c13 100644 (file)
@@ -26,7 +26,7 @@ class AppLogger : public ILogger
         void write(std::string time, ILogger::Level level, std::string message)
         {
             std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
-                      << message;
+                    << message;
         }
 };
 std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
@@ -34,7 +34,7 @@ std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
 class SimLightResource
 {
     public:
-        void startTest(std::string &configPath)
+        void startTest()
         {
             printMenu();
             bool cont = true;
@@ -50,19 +50,9 @@ class SimLightResource
 
                 switch (choice)
                 {
-                    case 1 : simulateResource(configPath); break;
+                    case 1 : simulateResource(); break;
                     case 2 : displayResource(); break;
-                    case 3 :
-                        try
-                        {
-                            deleteResource();
-                        }
-                        catch (InvalidArgsException &e)
-                        {
-                            std::cout << "InvalidArgsException occured [code : " << e.code() <<
-                                      " Detail: " << e.what() << "]" << std::endl;
-                        }
-                        break;
+                    case 3 : deleteResource(); break;
                     case 4 : updateAttributePower(); break;
                     case 5 : updateAttributeIntensity(); break;
                     case 6 : automateResourceUpdate(); break;
@@ -124,17 +114,17 @@ class SimLightResource
                                     const SimulatorResourceModel &resModel)
         {
             std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
-                      << " Count : " << resModel.size() << std::endl;
+                    << " Count : " << resModel.size() << std::endl;
             std::cout << "#### Modified attributes are ####" << std::endl;
             for (auto & attribute : resModel.getAttributes())
             {
                 std::cout << attribute.second.getName() << " :  "
-                          << attribute.second.valueToString().c_str() << std::endl;
+                        << attribute.second.valueToString().c_str() << std::endl;
             }
             std::cout << "########################" << std::endl;
         }
 
-        void simulateResource(std::string &configPath)
+        void simulateResource()
         {
             SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
                         &SimLightResource::onResourceModelChanged, this, std::placeholders::_1,
@@ -142,21 +132,24 @@ class SimLightResource
 
             try
             {
+                std::string configPath;
+                std::cout << "Enter RAML path: ";
+                std::cin>>configPath;
                 SimulatorResourceServerSP resource =
-                    SimulatorManager::getInstance()->createResource(configPath, callback);
+                        SimulatorManager::getInstance()->createResource(configPath, callback);
                 m_resources.push_back(resource);
                 std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
-                          << std::endl;
+                        << std::endl;
             }
             catch (InvalidArgsException &e)
             {
                 std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
-                          << e.what() << "]" << std::endl;
+                        << e.what() << "]" << std::endl;
             }
             catch (SimulatorException &e)
             {
                 std::cout << "SimulatorException occured [code : " << e.code() << " Detail: "
-                          << e.what() << "]" << std::endl;
+                        << e.what() << "]" << std::endl;
             }
         }
 
@@ -204,7 +197,7 @@ class SimLightResource
                         {
                             SimulatorManager::getInstance()->deleteResource(resourceType);
                             std::cout << "Resources of type \"" << resourceType << "\"" <<
-                                      " deleted successfully! " << std::endl;
+                                    " deleted successfully! " << std::endl;
                             std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
                             while (ite != m_resources.end())
                             {
@@ -219,12 +212,12 @@ class SimLightResource
                         catch (InvalidArgsException &e)
                         {
                             std::cout << "InvalidArgsException occured [code : " << e.code()
-                                      << " Detail: " << e.what() << "]" << std::endl;
+                                    << " Detail: " << e.what() << "]" << std::endl;
                         }
                         catch (SimulatorException &e)
                         {
                             std::cout << "SimulatorException occured [code : " << e.code()
-                                      << " Detail: " << e.what() << "]" << std::endl;
+                                    << " Detail: " << e.what() << "]" << std::endl;
                         }
                     } break;
 
@@ -257,7 +250,7 @@ class SimLightResource
             }
 
             std::cout << "Setting the new values from allowed values list to power attribute" <<
-                      std::endl;
+                    std::endl;
             // Update all possible values from allowed values
             for (int index = 0; index < allowedValuesSize; index++)
             {
@@ -303,7 +296,7 @@ class SimLightResource
             }
 
             std::cout << "Setting the new values from allowed values list to intensity attribute"
-                      << std::endl;
+                    << std::endl;
             // Update all possible values from allowed values
             for (int index = min; index <= max; index++)
             {
@@ -350,7 +343,7 @@ class SimLightResource
             // Attributes
             SimulatorResourceModel resModel = resource->getModel();
             std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                resModel.getAttributes();
+                    resModel.getAttributes();
             std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
             for (auto & attribute : attributes)
             {
@@ -374,7 +367,7 @@ class SimLightResource
                                          const int id)
         {
             std::cout << "Update automation is completed [URI: " << uri.c_str()
-                      << "  AutomationID: " << id << "] ###" << std::endl;
+                    << "  AutomationID: " << id << "] ###" << std::endl;
         }
 
         void automateResourceUpdate()
@@ -392,16 +385,16 @@ class SimLightResource
 
             try
             {
-                int id = m_resources[index - 1]->startUpdateAutomation(type,
+                int id = m_resources[index - 1]->startUpdateAutomation(type, 500,
                          std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
-                                   std::placeholders::_1, std::placeholders::_2));
+                                 std::placeholders::_1, std::placeholders::_2));
 
                 std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
             }
             catch (SimulatorException &e)
             {
                 std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
-                          e.what() << "]" << std::endl;
+                        e.what() << "]" << std::endl;
             }
         }
 
@@ -414,7 +407,7 @@ class SimLightResource
             SimulatorResourceServerSP resource = m_resources[index - 1];
             SimulatorResourceModel resModel = resource->getModel();
             std::map<std::string, SimulatorResourceModel::Attribute> attributes =
-                resModel.getAttributes();
+                    resModel.getAttributes();
             int size = 0;
             for (auto & attribute : attributes)
             {
@@ -429,7 +422,7 @@ class SimLightResource
 
             int choice = -1;
             std::cout << "Select the attribute which you want to automate for updation: " <<
-                      std::endl;
+                    std::endl;
             std::cin >> choice;
             if (choice < 0 || choice > size)
             {
@@ -457,20 +450,20 @@ class SimLightResource
                 type = AutomationType::RECURRENT;
 
             std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
-                      std::endl;
+                    std::endl;
 
             try
             {
 
-                int id = resource->startUpdateAutomation(attributeName, type,
+                int id = resource->startUpdateAutomation(attributeName, type, 500,
                          std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
-                                   std::placeholders::_1, std::placeholders::_2));
+                                std::placeholders::_1, std::placeholders::_2));
                 std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
             }
             catch (SimulatorException &e)
             {
                 std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
-                          e.what() << "]" << std::endl;
+                        e.what() << "]" << std::endl;
             }
         }
 
@@ -494,7 +487,7 @@ class SimLightResource
             if (!ids.size())
             {
                 std::cout << "No automation operation is going on this resource right now!" <<
-                          std::endl;
+                        std::endl;
                 return;
             }
 
@@ -514,7 +507,7 @@ class SimLightResource
             std::ostringstream out;
             out << "ID:  " << (int) observerInfo.id << std::endl;
             out << " [address: " << observerInfo.address << " port: " << observerInfo.port
-                << "]" << std::endl;
+                    << "]" << std::endl;
             std::cout << out.str();
         }
 
@@ -537,7 +530,7 @@ class SimLightResource
             for (auto & observerInfo : observersList)
             {
                 std::cout << " ID :  " << (int) observerInfo.id << " [address: " <<
-                          observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
+                        observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
             }
             std::cout << "########################" << std::endl;
         }
@@ -553,12 +546,6 @@ void printMainMenu()
     std::cout << "2. Set Logger" << std::endl;
     std::cout << "3. Help" << std::endl;
     std::cout << "0. Exit" << std::endl;
-    std::cout <<
-              "To set the Resource from RAML file, run the service provider with argument of Path of Raml File."
-              << std::endl;
-    std::cout <<
-              "Example: ./simulator-server PATH-TO-RAML-FILE"
-              << std::endl;
     std::cout << "######################################" << std::endl;
 }
 
@@ -597,17 +584,6 @@ void setLogger()
 
 int main(int argc, char *argv[])
 {
-    std::string configPath = "";
-
-    if (argc == 2)
-    {
-        char *value = argv[1];
-        configPath.append(value);
-    }
-    else
-    {
-        configPath = "";
-    }
     SimLightResource lightResource;
 
     printMainMenu();
@@ -624,7 +600,7 @@ int main(int argc, char *argv[])
 
         switch (choice)
         {
-            case 1: lightResource.startTest(configPath);
+            case 1: lightResource.startTest();
                 std::cout << "Welcome back to main menu !" << std::endl;
                 break;
             case 2: setLogger(); break;
index fcdfb6b..d596ed9 100644 (file)
@@ -202,7 +202,7 @@ class SimulatorResourceModel
 
                 bool compare(Attribute &attribute);
 
-                std::vector<ValueVariant> getAllowedValues();
+                std::vector<ValueVariant> getAllowedValues() const;
 
                 int getUpdateFrequencyTime() {return m_updateInterval;}
                 void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
@@ -231,7 +231,7 @@ class SimulatorResourceModel
                         ValueVariant &at(unsigned int index);
                         int size() const;
                         std::vector<std::string> toString() const;
-                        std::vector<ValueVariant> getValues();
+                        std::vector<ValueVariant> getValues() const;
                     private:
                         std::vector<ValueVariant> m_values;
                 };
@@ -291,7 +291,7 @@ class SimulatorResourceModel
           * @param attr  - Attribute pointer
           *
           */
-        void addAttribute(const Attribute &attribute);
+        void addAttribute(const Attribute &attribute, bool overwrite = false);
 
         /**
          * API to set range of attribute value.
index 715e8bb..b6f61a1 100644 (file)
@@ -199,7 +199,7 @@ class SimulatorResourceServer
          * @return ID representing update automation session.
          * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
          */
-        virtual int startUpdateAutomation(AutomationType type,
+        virtual int startUpdateAutomation(AutomationType type, int updateInterval,
                                           updateCompleteCallback callback) = 0;
 
         /**
@@ -209,6 +209,7 @@ class SimulatorResourceServer
          *
          * @param attrName - Name of the attribute to be automated.
          * @param type - Automation type.
+         * @param updateInterval -Interval time in milliseconds for attribute value update automation.
          * @param callback - Callback to get notifiy when update automation is finished.
          * @param id - Identifier for automation.
          *
@@ -216,7 +217,7 @@ class SimulatorResourceServer
          * NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
          */
         virtual int startUpdateAutomation(const std::string &attrName, AutomationType type,
-                                          updateCompleteCallback callback) = 0;
+                                          int updateInterval, updateCompleteCallback callback) = 0;
 
         /**
          * API to get the Ids of all ongoing resource update automation .
index 4366174..6822dfb 100644 (file)
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
 Bundle-ManifestVersion: 2
 Bundle-Name: ClientControllerPlugin
 Bundle-SymbolicName: ClientControllerPlugin;singleton:=true
-Bundle-Version: 0.1.0
+Bundle-Version: 1.0.0.qualifier
 Bundle-Activator: oic.simulator.clientcontroller.Activator
 Require-Bundle: org.eclipse.ui,
  org.eclipse.core.runtime
index 9b8bdb4..c7d225f 100644 (file)
@@ -47,7 +47,6 @@ import oic.simulator.clientcontroller.utils.Utility;
 import org.eclipse.jface.resource.ImageDescriptor;
 import org.eclipse.swt.graphics.Image;
 import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.InvalidArgsException;
 import org.oic.simulator.ResourceAttribute;
 import org.oic.simulator.ResourceAttribute.Range;
 import org.oic.simulator.ResourceAttribute.Type;
@@ -398,7 +397,7 @@ public class ResourceManager {
         // TODO: For debugging
         if (null != attributeMap) {
             RemoteResourceAttribute.printAttributes(attributeMap);
-            System.out.println("Attributes found: ");
+            System.out.println("Attributes found: " + (null != attributeMap));
             System.out.println("No of attributes: " + attributeMap.size());
 
             resource.setResourceAttributesMap(attributeMap);
@@ -582,7 +581,7 @@ public class ResourceManager {
     }
 
     public boolean isResourceObserved(String resourceURI) {
-        boolean observed;
+        boolean observed = false;
         synchronized (observedResourceURIList) {
             observed = observedResourceURIList.contains(resourceURI);
         }
@@ -1483,16 +1482,6 @@ public class ResourceManager {
         }
         try {
             resourceN.stopVerification(autoId);
-        } catch (InvalidArgsException e) {
-            Activator
-            .getDefault()
-            .getLogManager()
-            .log(Level.ERROR.ordinal(),
-                    new Date(),
-                    "[" + e.getClass().getSimpleName() + "]"
-                            + e.code().toString() + "-"
-                            + e.message());
-            return;
         } catch (SimulatorException e) {
             Activator
                     .getDefault()
index 9b0d603..6316674 100644 (file)
@@ -143,7 +143,8 @@ public class FindResourcePage extends WizardPage {
          */
 
         // TODO: Temporarily adding a resourceType for testing
-       // resourceTypeCmb.add("oic.r.light");
+        // resourceTypeCmb.add("oic.r.light");
+        // Currently for standard resources we are using resource type as sample.light.
         resourceTypeCmb.add("sample.light");
 
         // By default, selecting the first item in the resourceType combo
index 3b01cff..26c11b4 100644 (file)
@@ -19,7 +19,6 @@ package oic.simulator.clientcontroller.view.dialogs;
 import java.util.List;
 
 import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.manager.ResourceManager;
 import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
 import oic.simulator.clientcontroller.utils.Constants;
 
@@ -30,6 +29,7 @@ import org.eclipse.jface.viewers.CheckboxCellEditor;
 import org.eclipse.jface.viewers.ColumnLabelProvider;
 import org.eclipse.jface.viewers.EditingSupport;
 import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
 import org.eclipse.jface.viewers.StyledCellLabelProvider;
 import org.eclipse.jface.viewers.TableViewer;
 import org.eclipse.jface.viewers.TableViewerColumn;
@@ -37,6 +37,8 @@ import org.eclipse.jface.viewers.TextCellEditor;
 import org.eclipse.jface.viewers.Viewer;
 import org.eclipse.jface.viewers.ViewerCell;
 import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
 import org.eclipse.swt.graphics.Image;
 import org.eclipse.swt.layout.GridData;
 import org.eclipse.swt.layout.GridLayout;
@@ -45,6 +47,7 @@ import org.eclipse.swt.widgets.Composite;
 import org.eclipse.swt.widgets.Control;
 import org.eclipse.swt.widgets.Shell;
 import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
 
 /**
  * This dialog is used for generating a POST request.
@@ -57,15 +60,12 @@ public class PostRequestDialog extends TitleAreaDialog {
             "Select"                                  };
     private final Integer[]             attTblColWidth = { 200, 200, 50 };
 
-    private ResourceManager             resourceManager;
-
     private List<PutPostAttributeModel> modelList      = null;
-
+    
     public PostRequestDialog(Shell parentShell,
             List<PutPostAttributeModel> modelList) {
         super(parentShell);
         this.modelList = modelList;
-        resourceManager = Activator.getDefault().getResourceManager();
     }
 
     @Override
@@ -204,11 +204,33 @@ public class PostRequestDialog extends TitleAreaDialog {
     class AttributeValueEditor extends EditingSupport {
         private final TableViewer viewer;
         private final CellEditor  editor;
-
+        private final Text txt;
         public AttributeValueEditor(TableViewer viewer) {
             super(viewer);
             this.viewer = viewer;
             editor = new TextCellEditor(viewer.getTable());
+            txt = (Text)editor.getControl();
+            if(null != txt) {
+                txt.addModifyListener(new ModifyListener() {
+                    @Override
+                    public void modifyText(ModifyEvent e) {                 
+                        IStructuredSelection selection = (IStructuredSelection)AttributeValueEditor.this.viewer.getSelection();
+                        PutPostAttributeModel att = (PutPostAttributeModel)selection.getFirstElement();             
+                        if(null == att) {
+                            return;
+                        }
+                        String newValue = txt.getText();
+                        if(null != newValue && !newValue.isEmpty()) {
+                            att.setModified(true);
+                        }
+                        else {
+                            att.setModified(false);
+                        }
+                        AttributeValueEditor.this.viewer.update(att, null);
+                    }
+                });
+              
+            }
         }
 
         @Override
@@ -234,14 +256,6 @@ public class PostRequestDialog extends TitleAreaDialog {
             // If there is a change, then its corresponding check box should be
             // checked.
             String newValue = String.valueOf(value);
-            String actualValue = resourceManager.getAttributeValue(
-                    resourceManager.getCurrentResourceInSelection(),
-                    model.getAttName());
-            if (newValue.equals(actualValue)) {
-                model.setModified(false);
-            } else {
-                model.setModified(true);
-            }
             model.setAttValue(newValue);
             viewer.update(element, null);
         }
index 940c1b3..ee700d1 100644 (file)
@@ -56,7 +56,7 @@ public class ImageManager {
                 .createFromURL(bundle.getEntry("icons/button_pressed.PNG")));
 
         // Resource icons based on the resource type
-        r.put(Constants.OIC_R_LIGHT, ImageDescriptor.createFromURL(bundle
+        r.put(Constants.SAMPLE_LIGHT, ImageDescriptor.createFromURL(bundle
                 .getEntry("/icons/light_16x16.png")));
 
         // Log View related icons
index ebc34e0..e6cca32 100644 (file)
@@ -44,7 +44,6 @@ import oic.simulator.serviceprovider.utils.Utility;
 import org.eclipse.swt.graphics.Image;
 import org.oic.simulator.IAutomation;
 import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.InvalidArgsException;
 import org.oic.simulator.ResourceAttribute;
 import org.oic.simulator.ResourceAttribute.Range;
 import org.oic.simulator.ResourceAttribute.Type;
@@ -483,7 +482,7 @@ public class ResourceManager {
     }
 
     public boolean isDisplayName(String displayName) {
-        boolean exist;
+        boolean exist = false;
         synchronized (displayNameMap) {
             exist = displayNameMap.containsKey(displayName);
         }
@@ -491,7 +490,7 @@ public class ResourceManager {
     }
 
     public String getCompleteUriFromDisplayName(String displayName) {
-        String completeURI;
+        String completeURI = null;
         synchronized (displayNameMap) {
             completeURI = displayNameMap.get(displayName);
         }
@@ -567,7 +566,7 @@ public class ResourceManager {
             @Override
             public void run() {
                 Map<String, SimulatorResource> resourceTypeMap;
-                SimulatorResourceServer[] simulatorResourceServers;
+                SimulatorResourceServer[] simulatorResourceServers = null;
                 try {
                     simulatorResourceServers = SimulatorManager.createResource(
                             configFilePath, noOfInstances,
@@ -1123,12 +1122,12 @@ public class ResourceManager {
     }
 
     public List<String> getURIList() {
-        List<String> list;
+        List<String> list = null;
         synchronized (orderedResourceUriMap) {
             Set<String> typeSet = orderedResourceUriMap.keySet();
             List<String> typeList = Utility.convertSetToList(typeSet);
             if (null == typeList || typeList.size() < 1) {
-                return null;
+                return list;
             }
             list = new ArrayList<String>();
 
@@ -1350,7 +1349,7 @@ public class ResourceManager {
                 String attrName = attribute.getAttributeName();
                 try {
                     autoId = resourceServerN.startAttributeAutomation(attrName,
-                            autoType, automationListener);
+                            autoType, autoUpdateInterval, automationListener);
                 } catch (SimulatorException e) {
                     Activator
                             .getDefault()
@@ -1471,7 +1470,7 @@ public class ResourceManager {
                 int autoId = -1;
                 try {
                     autoId = resourceServer.startResourceAutomation(
-                            AutomationType.NORMAL, automationListener);
+                            AutomationType.NORMAL, 500, automationListener);
                 } catch (SimulatorException e) {
                     Activator
                             .getDefault()
@@ -1644,4 +1643,4 @@ public class ResourceManager {
     public void shutdown() {
         threadHandle.interrupt();
     }
-}
+}
\ No newline at end of file
index b444073..09fecfc 100644 (file)
@@ -103,5 +103,5 @@ public class Constants {
 
     public static final String         SPLIT_BY_DOT_PATTERN             = "\\.";
 
-    public static final String         OIC_R_LIGHT                      = "oic.r.light";
+    public static final String         SAMPLE_LIGHT                      = "sample.light";
 }
\ No newline at end of file
index a62f0ae..be7dae8 100644 (file)
@@ -207,12 +207,9 @@ public class DeleteResourcePage extends WizardPage {
         if (deleteCategory == DeleteCategory.ALL) {
             done = true;
         } else if (deleteCategory == DeleteCategory.BY_TYPE) {
-            int selectedItemIndex = resourceTypeCmb.getSelectionIndex();
-            if (selectedItemIndex >= 0) {
-                deleteCandidate = resourceTypeCmb.getItem(selectedItemIndex);
-                if (null != deleteCandidate && deleteCandidate.length() > 0) {
-                    done = true;
-                }
+            deleteCandidate = resourceTypeCmb.getText();
+            if (null != deleteCandidate && deleteCandidate.length() > 0) {
+                done = true;
             }
         } else if (deleteCategory == DeleteCategory.BY_URI) {
             deleteCandidate = resourceUriTxt.getText();
index 0203afa..5732eff 100644 (file)
@@ -54,7 +54,6 @@ class attribute_value_visitor : public boost::static_visitor<jobject>
             return static_cast<jobject>(str);
         }
 
-#if 0
         // Boolean type value conversion
         jobject operator ()(const bool &value) const
         {
@@ -62,7 +61,7 @@ class attribute_value_visitor : public boost::static_visitor<jobject>
                                               gSimulatorClassRefs.classBooleanCtor, value);
             return result;
         }
-
+#if 0
         // SimulatorResourceModel::Attribute type value conversion
         jobject operator ()(const SimulatorResourceModel::Attribute &value) const
         {
index 860874e..b0fd74b 100644 (file)
@@ -28,6 +28,7 @@ typedef struct
     jclass classObject;
     jclass classInteger;
     jclass classDouble;
+    jclass classBoolean;
     jclass classString;
     jclass classHashMap;
     jclass classVector;
@@ -52,6 +53,7 @@ typedef struct
 
     jmethodID classIntegerCtor;
     jmethodID classDoubleCtor;
+    jmethodID classBooleanCtor;
     jmethodID classHashMapCtor;
     jmethodID classHashMapPut;
     jmethodID classVectorCtor;
index be28c6d..c954a97 100644 (file)
@@ -27,12 +27,12 @@ jobject JDeviceInfo::toJava(DeviceInfo &deviceInfo)
     if (!m_env)
         return nullptr;
 
-    jmethodID constr = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
-    if (constr)
+    jmethodID deviceInfoMId = m_env->GetMethodID(gSimulatorClassRefs.classDeviceInfo, "<init>", "(V)V");
+    if (!deviceInfoMId)
         return nullptr;
 
-    jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, constr);
-    if (jDeviceInfo)
+    jobject jDeviceInfo = (jobject) m_env->NewObject(gSimulatorClassRefs.classDeviceInfo, deviceInfoMId);
+    if (!jDeviceInfo)
         return nullptr;
 
     setFieldValue(jDeviceInfo, "mName", deviceInfo.getName());
index 6ae6e58..0fc5796 100644 (file)
@@ -712,6 +712,11 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
         return JNI_ERR;
     }
 
+    if (false == getClassRef(env, "java/lang/Boolean", gSimulatorClassRefs.classBoolean))
+    {
+        return JNI_ERR;
+    }
+
     if (false == getClassRef(env, "java/lang/String", gSimulatorClassRefs.classString))
     {
         return JNI_ERR;
@@ -829,6 +834,11 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
     if (!gSimulatorClassRefs.classDoubleCtor)
         return JNI_ERR;
 
+    gSimulatorClassRefs.classBooleanCtor= env->GetMethodID(gSimulatorClassRefs.classBoolean, "<init>",
+                                          "(Z)V");
+    if (!gSimulatorClassRefs.classBooleanCtor)
+        return JNI_ERR;
+
     gSimulatorClassRefs.classHashMapCtor = env->GetMethodID(gSimulatorClassRefs.classHashMap, "<init>",
                                            "()V");
     if (!gSimulatorClassRefs.classHashMapCtor)
index 3b62939..63215b6 100644 (file)
@@ -739,7 +739,7 @@ Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_setConfigInfo
     if (!jConfigPath)
     {
         throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM,
-                                  "Configuration file path is empty!");
+                                  "Configuration file path is null!");
         return;
     }
 
@@ -889,3 +889,9 @@ Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
     }
 }
 
+JNIEXPORT void JNICALL Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose
+(JNIEnv *env, jobject thiz)
+{
+    JniSimulatorRemoteResource *resource = GetHandle<JniSimulatorRemoteResource>(env, thiz);
+    delete resource;
+}
\ No newline at end of file
index 50befef..b1fbecd 100644 (file)
@@ -73,6 +73,10 @@ JNIEXPORT void JNICALL
 Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_stopVerification
 (JNIEnv *env, jobject thiz, jint jId);
 
+JNIEXPORT void JNICALL
+Java_org_oic_simulator_clientcontroller_SimulatorRemoteResource_dispose
+(JNIEnv *, jobject);
+
 #ifdef __cplusplus
 }
 #endif
index 9d67689..65b9d9d 100644 (file)
@@ -316,6 +316,12 @@ Java_org_oic_simulator_SimulatorResourceModel_addAttributeString
         return;
     }
 
+    if (!jvalue)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!");
+        return;
+    }
+
     SimulatorResourceModelSP resModelPtr;
     resModelPtr = JSimulatorResourceModel::getResourceModelPtr(env, thiz);
     if (!resModelPtr)
index c9b08c9..209ef47 100644 (file)
@@ -234,6 +234,12 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_addAttributeStrin
         return;
     }
 
+    if (!jValue)
+    {
+        throwInvalidArgsException(env, SIMULATOR_INVALID_PARAM, "Attribute value cannot be null!");
+        return;
+    }
+
     SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env,
                                          jobject);
     if (!resource)
@@ -482,7 +488,7 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesS
 
 JNIEXPORT jint JNICALL
 Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *env, jobject object, jint automationType, jobject listener)
+(JNIEnv *env, jobject object, jint automationType, jint updateInterval, jobject listener)
 {
     SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
     if (!resource)
@@ -514,7 +520,7 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAuto
 
     try
     {
-        automationId = resource->startUpdateAutomation(type, callback);
+        automationId = resource->startUpdateAutomation(type, updateInterval, callback);
     }
     catch (InvalidArgsException &e)
     {
@@ -533,7 +539,7 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAuto
 
 JNIEXPORT jint JNICALL
 Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *env, jobject object, jstring attrName, jint automationType, jobject listener)
+(JNIEnv *env, jobject object, jstring attrName, jint automationType, jint updateInterval, jobject listener)
 {
     SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
     if (!resource)
@@ -572,7 +578,7 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAut
     int automationId = -1;
     try
     {
-        automationId = resource->startUpdateAutomation(attrNamePtr, type, callback);
+        automationId = resource->startUpdateAutomation(attrNamePtr, type, updateInterval, callback);
     }
     catch (InvalidArgsException &e)
     {
@@ -639,7 +645,25 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_removeAttribute
     }
 
     std::string str = env->GetStringUTFChars(jKey, NULL);
-    resource->removeAttribute(str);
+    try
+    {
+        resource->removeAttribute(str);
+    }
+    catch (InvalidArgsException &e)
+    {
+        throwInvalidArgsException(env, e.code(), e.what());
+        return;
+    }
+    catch (SimulatorException &e)
+    {
+        throwSimulatorException(env, e.code(), e.what());
+        return;
+    }
+    catch (...)
+    {
+        throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+        return;
+    }
 }
 
 JNIEXPORT jobjectArray JNICALL
index 765d2b6..298071a 100644 (file)
@@ -98,11 +98,11 @@ Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_setAllowedValuesS
 
 JNIEXPORT jint JNICALL
 Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *, jobject, jint, jobject);
+(JNIEnv *, jobject, jint, jint, jobject);
 
 JNIEXPORT jint JNICALL
 Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *, jobject, jstring, jint, jobject);
+(JNIEnv *, jobject, jstring, jint, jint, jobject);
 
 JNIEXPORT void JNICALL
 Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
index a276e0f..63961e9 100644 (file)
@@ -157,9 +157,7 @@ public class SimulatorResourceModel {
     protected void finalize() throws Throwable {
         try {
             dispose();
-        } catch(Throwable t){
-            throw t;
-        } finally{
+        } finally {
             super.finalize();
         }
     }
index 096e65e..1697681 100644 (file)
@@ -417,9 +417,7 @@ public class SimulatorRemoteResource {
     protected void finalize() throws Throwable {
         try {
             dispose();
-        } catch(Throwable t){
-            throw t;
-        } finally{
+        } finally {
             super.finalize();
         }
     }
index 0d9accd..d601b53 100644 (file)
@@ -334,6 +334,8 @@ public class SimulatorResourceServer {
      * @param typeOfAutomation
      *            {@link AutomationType} indicating whether the automation is
      *            one-time or recursive.
+     * @param updateInterval
+     *            Interval time in milliseconds for attribute value update automation.
      * @param listener
      *            Listener to be notified when automation ends.
      *
@@ -346,9 +348,9 @@ public class SimulatorResourceServer {
      *             This exception will be thrown for other errors.
      */
     public int startResourceAutomation(AutomationType typeOfAutomation,
-            IAutomation listener) throws InvalidArgsException,
+            int updateInterval, IAutomation listener) throws InvalidArgsException,
             SimulatorException {
-        return startResourceAutomation(typeOfAutomation.getValue(), listener);
+        return startResourceAutomation(typeOfAutomation.getValue(), updateInterval, listener);
     }
 
     /**
@@ -361,6 +363,8 @@ public class SimulatorResourceServer {
      * @param typeOfAutomation
      *            {@link AutomationType} indicating whether the automation is
      *            one-time or recursive.
+     * @param updateInterval
+     *            Interval time in milliseconds for attribute value update automation.
      * @param listener
      *            Listener to be notified when automation ends.
      *
@@ -373,10 +377,11 @@ public class SimulatorResourceServer {
      *             This exception will be thrown for other errors.
      */
     public int startAttributeAutomation(String attrName,
-            AutomationType typeOfAutomation, IAutomation listener)
+            AutomationType typeOfAutomation, int updateInterval,
+            IAutomation listener)
             throws InvalidArgsException, SimulatorException {
         return startAttributeAutomation(attrName, typeOfAutomation.getValue(),
-                listener);
+                updateInterval, listener);
     }
 
     /**
@@ -463,20 +468,18 @@ public class SimulatorResourceServer {
             SimulatorException;
 
     private native int startResourceAutomation(int typeOfAutomation,
-            IAutomation listener) throws InvalidArgsException,
+            int updateInterval, IAutomation listener) throws InvalidArgsException,
             SimulatorException;
 
     private native int startAttributeAutomation(String attrName,
-        int typeOfAutomation, IAutomation listener)
+        int typeOfAutomation, int updateInterval, IAutomation listener)
         throws InvalidArgsException, SimulatorException;
 
     @Override
     protected void finalize() throws Throwable {
         try {
             dispose();
-        } catch(Throwable t){
-            throw t;
-        } finally{
+        } finally {
             super.finalize();
         }
     }
index d2eec8f..401e448 100755 (executable)
@@ -118,7 +118,7 @@ namespace RAML
                     if (*it == reqValue)\r
                         break;\r
                 }\r
-                if (m_required.end() == it)\r
+                if (m_required.end() != it)\r
                 {\r
                     m_required.push_back(reqValue);\r
                 }\r
index d2463b2..b0a0e50 100755 (executable)
@@ -124,7 +124,7 @@ namespace RAML
                     if (*it == reqValue)\r
                         break;\r
                 }\r
-                if (m_required.end() == it)\r
+                if (m_required.end() != it)\r
                 {\r
                     m_required.push_back(reqValue);\r
                 }\r
index 5943264..03abd64 100644 (file)
 
 #include "attribute_generator.h"
 
-AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attribute)
+AttributeGenerator::AttributeGenerator(const SimulatorResourceModel::Attribute &attribute)
     :   m_name(attribute.getName()),
         m_min(INT_MIN),
         m_max(INT_MAX),
         m_rangeIndex(-1),
-        m_nextAllowedValueIndex(0),
-        m_prevAllowedValueIndex(0),
+        m_allowedValueIndex(0),
         m_hasRange(false),
         m_hasAllowedValue(false)
 {
@@ -47,7 +46,6 @@ AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attrib
         {
             m_hasAllowedValue = true;
         }
-        m_prevAllowedValueIndex = m_allowedValues.size();
     }
 }
 
@@ -58,7 +56,7 @@ bool AttributeGenerator::hasNext()
         return true;
     }
 
-    if (m_hasAllowedValue && m_nextAllowedValueIndex < m_allowedValues.size())
+    if (m_hasAllowedValue && m_allowedValueIndex < m_allowedValues.size())
     {
         return true;
     }
@@ -77,28 +75,113 @@ bool AttributeGenerator::next(SimulatorResourceModel::Attribute &attribute)
     }
     else if (m_hasAllowedValue)
     {
-        attribute.setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+        attribute.setValue(m_allowedValues[m_allowedValueIndex++]);
         return true;
     }
 
     return false;
 }
 
-bool AttributeGenerator::previous(SimulatorResourceModel::Attribute &attribute)
+SimulatorResourceModel::Attribute AttributeGenerator::current()
 {
+    SimulatorResourceModel::Attribute attribute;
+
     attribute.setName(m_name);
+    if (m_hasRange)
+    {
+        attribute.setValue(m_rangeIndex);
+    }
+    else if (m_hasAllowedValue)
+    {
+        attribute.setValue(m_allowedValues[m_allowedValueIndex]);
+    }
+
+    return attribute;
+}
 
+void AttributeGenerator::reset()
+{
     if (m_hasRange)
     {
-        attribute.setValue(m_rangeIndex - 1);
-        return true;
+        m_rangeIndex = m_min;
     }
     else if (m_hasAllowedValue)
     {
-        attribute.setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+        m_allowedValueIndex = 0;
+    }
+}
+
+AttributeCombinationGen::AttributeCombinationGen(
+        const std::vector<SimulatorResourceModel::Attribute> &attributes)
+{
+    for (auto &attr : attributes)
+    {
+        AttributeGenerator attrGen(attr);
+        m_attrGenList.push_back(attr);
+    }
+
+    m_index = -1;
+}
+
+bool AttributeCombinationGen::next(SimulatorResourceModel &resModel)
+{
+    if (!m_attrGenList.size())
+    {
+        return false;
+    }
+
+    std::lock_guard<std::mutex> lock(m_lock);
+
+    // This block will execute for only first time
+    if (-1 == m_index)
+    {
+        for (int index = 0; index < m_attrGenList.size(); index++)
+        {
+            // Add the attribute on resource model
+            addAttributeToModel(index);
+        }
+
+        m_index = m_attrGenList.size() - 1;
+        resModel = m_resModel;
+        return true;
+    }
+
+    // Get the next attribute from statck top element
+    if (m_attrGenList[m_index].hasNext())
+    {
+        addAttributeToModel(m_index);
+        resModel = m_resModel;
+        return true;
+    }
+    else
+    {
+        for (int index = m_index; index >= 0; index--)
+        {
+            if (!m_attrGenList[index].hasNext())
+            {
+                if (!index)
+                    return false;
+
+                m_attrGenList[index].reset();
+                addAttributeToModel(index);
+            }
+            else
+            {
+                addAttributeToModel(index);
+                break;
+            }
+        }
+
+        resModel = m_resModel;
         return true;
     }
 
     return false;
 }
 
+void AttributeCombinationGen::addAttributeToModel(int index)
+{
+    SimulatorResourceModel::Attribute attribute;
+    m_attrGenList[index].next(attribute);
+    m_resModel.addAttribute(attribute, true);
+}
index 3f66372..fab888f 100644 (file)
 class AttributeGenerator
 {
     public:
-        AttributeGenerator(SimulatorResourceModel::Attribute &attribute);
+        AttributeGenerator(const SimulatorResourceModel::Attribute &attribute);
         bool hasNext();
         bool next(SimulatorResourceModel::Attribute &attribute);
-        bool previous(SimulatorResourceModel::Attribute &attribute);
+        SimulatorResourceModel::Attribute current();
         void reset();
 
     private:
         std::string m_name;
-        SimulatorResourceModel::Attribute::ValueType m_type;
         int m_min;
         int m_max;
         int m_rangeIndex;
-        int m_nextAllowedValueIndex;
-        int m_prevAllowedValueIndex;
+        int m_allowedValueIndex;
         bool m_hasRange;
         bool m_hasAllowedValue;
         std::vector<SimulatorResourceModel::Attribute::ValueVariant> m_allowedValues;
 };
 
+class AttributeCombinationGen
+{
+    public:
+        AttributeCombinationGen(const std::vector<SimulatorResourceModel::Attribute> &attributes);
+        bool next(SimulatorResourceModel &resModel);
+
+    private:
+        void addAttributeToModel(int index);
+
+        std::mutex m_lock;
+        std::vector<AttributeGenerator> m_attrGenList;
+        int m_index;
+        SimulatorResourceModel m_resModel;
+};
+
 #endif
 
index 3c8d63b..56bee77 100644 (file)
@@ -75,63 +75,44 @@ void PUTRequestGenerator::SendAllRequests()
     OC_LOG(DEBUG, TAG, "Sending OP_START event");
     m_callback(m_id, OP_START);
 
-    // Create attribute generator for value manipulation
-    std::vector<AttributeGenerator> attributeGenList;
+    // Create attribute combination generator for generating resource model
+    // with different attribute values
+    std::vector<SimulatorResourceModel::Attribute> attributes;
     for (auto &attributeElement : m_rep->getAttributes())
-        attributeGenList.push_back(AttributeGenerator(attributeElement.second));
+    {
+        attributes.push_back(attributeElement.second);
+    }
 
-    if (!attributeGenList.size())
+    if (!attributes.size())
     {
         OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
         return;
     }
 
-    bool hasNext = false;
-
     do
     {
-        if (!m_stopRequested)
+        if (m_stopRequested)
         {
-            // Get the next possible queryParameter
-            std::map<std::string, std::string> queryParam = m_queryParamGen.next();
-
-            while (true)
-            {
-                SimulatorResourceModelSP repModel(new SimulatorResourceModel);
-                for (auto & attributeGen : attributeGenList)
-                {
-                    if (attributeGen.hasNext())
-                    {
-                        SimulatorResourceModel::Attribute attribute;
-                        if (true == attributeGen.next(attribute))
-                            repModel->addAttribute(attribute);
-
-                        hasNext = true;
-                    }
-                    else
-                    {
-                        SimulatorResourceModel::Attribute attribute;
-                        if (true == attributeGen.previous(attribute))
-                            repModel->addAttribute(attribute);
-                    }
-                }
-
-                if (hasNext)
-                {
-                    // Send the request
-                    m_requestSender->sendRequest(queryParam, repModel,
-                            std::bind(&PUTRequestGenerator::onResponseReceived, this,
-                            std::placeholders::_1, std::placeholders::_2), true);
-
-                    m_requestCnt++;
-                    hasNext = false;
-                    continue;
-                }
-                else
-                {
-                    break;
-                }
-            }
+            break;
+        }
+
+        // Get the next possible queryParameter
+        std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+        AttributeCombinationGen attrCombGen(attributes);
+
+        // Get the new model from attribute combination generator
+        SimulatorResourceModel resModel;
+        while (!m_stopRequested && attrCombGen.next(resModel))
+        {
+            SimulatorResourceModelSP repModel(new SimulatorResourceModel(resModel));
+
+            // Send the request
+            m_requestSender->sendRequest(queryParam, repModel,
+                    std::bind(&PUTRequestGenerator::onResponseReceived, this,
+                    std::placeholders::_1, std::placeholders::_2), true);
+
+            m_requestCnt++;
         }
     }
     while (m_queryParamGen.hasNext());
index d4472f8..178dccb 100644 (file)
@@ -302,8 +302,8 @@ int SimulatorRemoteResourceImpl::startVerification(RequestType type,
             if (m_getRequestSender)
             {
                 return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
-                                                        m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
-                                                        localCallback);
+                                    m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
+                                    localCallback);
             }
             break;
 
@@ -311,9 +311,9 @@ int SimulatorRemoteResourceImpl::startVerification(RequestType type,
             if (m_putRequestSender)
             {
                 return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
-                                                        m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
-                                                        m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
-                                                        localCallback);
+                                    m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
+                                    m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
+                                    localCallback);
             }
             break;
 
@@ -321,9 +321,9 @@ int SimulatorRemoteResourceImpl::startVerification(RequestType type,
             if (m_postRequestSender)
             {
                 return m_autoRequestGenMngr->startOnPOST(m_putRequestSender,
-                        m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
-                        m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
-                        localCallback);
+                                    m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
+                                    m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
+                                    localCallback);
             }
             break;
 
@@ -356,7 +356,7 @@ void SimulatorRemoteResourceImpl::configure(const std::string &path)
 {
     if (path.empty())
     {
-        OC_LOG(ERROR, TAG, "Invalid path given for configuration !");
+        OC_LOG(ERROR, TAG, "Invalid path given for configuration!");
         throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Empty path string!");
     }
 
index dcd7988..2a1a67d 100644 (file)
@@ -19,6 +19,8 @@
  ******************************************************************/
 
 #include "simulator_resource_model.h"
+#include "simulator_exceptions.h"
+#include "logger.h"
 #include "OCPlatform.h"
 #include <sstream>
 #include <boost/lexical_cast.hpp>
@@ -127,6 +129,8 @@ class range_validation : public boost::static_visitor<bool>
         {
             std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
                 = m_attrItem.getAllowedValues();
+            if(0 == values.size())
+                return true;
             for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
             {
                 SimulatorResourceModel::Attribute::ValueVariant vVal = value;
@@ -145,6 +149,8 @@ class range_validation : public boost::static_visitor<bool>
         {
             std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
                 = m_attrItem.getAllowedValues();
+            if(0 == values.size())
+                return true;
             for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
             {
                 std::string val = boost::get<std::string>(vVal);
@@ -183,7 +189,7 @@ std::vector<std::string> SimulatorResourceModel::Attribute::AllowedValues::toStr
 }
 
 std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::AllowedValues::getValues()
+SimulatorResourceModel::Attribute::AllowedValues::getValues() const
 {
     return m_values;
 }
@@ -259,7 +265,7 @@ bool SimulatorResourceModel::Attribute::compare(SimulatorResourceModel::Attribut
 }
 
 std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::getAllowedValues()
+SimulatorResourceModel::Attribute::getAllowedValues() const
 {
     return m_allowedValues.getValues();
 }
@@ -281,10 +287,10 @@ const
     return m_attributes;
 }
 
-void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute)
+void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute, bool overwrite)
 {
     if (!attribute.getName().empty() &&
-        m_attributes.end() == m_attributes.find(attribute.getName()))
+        (m_attributes.end() == m_attributes.find(attribute.getName()) || overwrite))
     {
         m_attributes[attribute.getName()] = attribute;
     }
@@ -311,9 +317,10 @@ void SimulatorResourceModel::updateAttributeFromAllowedValues(const std::string
 
 void SimulatorResourceModel::removeAttribute(const std::string &attrName)
 {
-   if (m_attributes.end() == m_attributes.find(attrName))
+   if (attrName.empty() || m_attributes.end() == m_attributes.find(attrName))
    {
-       return;
+       OC_LOG(ERROR, TAG, "Attribute name is empty or not found in model!");
+       throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Attribute not found in model!");
    }
 
     m_attributes.erase(attrName);
@@ -377,6 +384,8 @@ SimulatorResourceModelSP SimulatorResourceModel::create(const OC::OCRepresentati
             attribute.setValue(attributeItem.getValue<double>());
         if (attributeItem.type() == OC::AttributeType::String)
             attribute.setValue(attributeItem.getValue<std::string>());
+        if (attributeItem.type() == OC::AttributeType::Boolean)
+            attribute.setValue(attributeItem.getValue<bool>());
 
         attribute.setName(attributeItem.attrname());
         resModel->m_attributes[attributeItem.attrname()] = attribute;
index c66711a..f2f2bc0 100644 (file)
@@ -20,6 +20,7 @@
 
 #include "resource_update_automation.h"
 #include "simulator_resource_server_impl.h"
+#include "attribute_generator.h"
 #include "simulator_exceptions.h"
 #include "simulator_logger.h"
 #include "logger.h"
@@ -92,7 +93,7 @@ void AttributeUpdateAutomation::updateAttribute()
         SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed.");
     }
 
-    // Notify application through callback
+    // Notify application
     if (m_callback)
         m_callback(m_resource->getURI(), m_id);
 
@@ -142,65 +143,61 @@ ResourceUpdateAutomation::ResourceUpdateAutomation(int id, SimulatorResourceServ
     :   m_resource(resource),
         m_type(type),
         m_id(id),
+        m_stopRequested(false),
         m_updateInterval(interval),
         m_callback(callback),
-        m_finishedCallback(finishedCallback) {}
+        m_finishedCallback(finishedCallback),
+        m_thread(nullptr) {}
 
 void ResourceUpdateAutomation::start()
 {
-    m_resModel = m_resource->getModel();
-    std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
-    if (0 == attributes.size())
+    SimulatorResourceModel resModel = m_resource->getModel();
+    std::map<std::string, SimulatorResourceModel::Attribute> attributesTable =
+            resModel.getAttributes();
+    if (0 == attributesTable.size())
     {
         OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
         throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
     }
 
-    int id = 0;
-    for (auto & attribute : attributes)
-    {
-        AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
-                    id, m_resource, attribute.first, m_type, m_updateInterval, nullptr,
-                    std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1)));
+    std::vector<SimulatorResourceModel::Attribute> attributes;
+    for (auto &attributeEntry : attributesTable)
+        attributes.push_back(attributeEntry.second);
 
-        m_attrUpdationList[id++] = attributeAutomation;
-        try
-        {
-            attributeAutomation->start();
-        }
-        catch (SimulatorException &e)
-        {
-            stop();
-            throw;
-        }
-    }
+    m_thread = new std::thread(&ResourceUpdateAutomation::updateAttributes, this, attributes);
 }
 
-void ResourceUpdateAutomation::finished(int id)
+void ResourceUpdateAutomation::stop()
 {
-    if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
-    {
-        m_attrUpdationList.erase(m_attrUpdationList.find(id));
-    }
-
-    if (!m_attrUpdationList.size())
-    {
-        // Notify application through callback
-        if (m_callback)
-            m_callback(m_resource->getURI(), m_id);
-
-        if (m_finishedCallback)
-            m_finishedCallback(m_id);
-    }
+    m_stopRequested = true;
+    if (m_thread)
+        m_thread->join();
 }
 
-void ResourceUpdateAutomation::stop()
+void ResourceUpdateAutomation::updateAttributes(
+        std::vector<SimulatorResourceModel::Attribute> attributes)
 {
-    // Stop all the attributes updation
-    for (auto & attrAutomation : m_attrUpdationList)
+    SimulatorResourceServerImpl *resourceImpl =
+        dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+
+    AttributeCombinationGen attrCombGen(attributes);
+    SimulatorResourceModel resModel;
+    while (!m_stopRequested && attrCombGen.next(resModel))
     {
-        (attrAutomation.second)->stop();
+        for (auto &attributeEntry : resModel.getAttributes())
+        {
+            resourceImpl->updateAttributeValue(attributeEntry.first, attributeEntry.second.getValue());
+        }
+
+        resourceImpl->notifyApp();
+        SLEEP_FOR(m_updateInterval);
     }
 
-    m_attrUpdationList.clear();
+    // Notify application
+    if (m_callback)
+        m_callback(m_resource->getURI(), m_id);
+
+    if (m_finishedCallback && !m_stopRequested)
+        m_finishedCallback(m_id);
 }
+
index ba80911..6ae1f0e 100644 (file)
@@ -66,17 +66,17 @@ class ResourceUpdateAutomation
 
         void stop();
 
-        void finished(int id);
-
     private:
+        void updateAttributes(std::vector<SimulatorResourceModel::Attribute> attributes);
+
         SimulatorResourceServer *m_resource;
         AutomationType m_type;
         int m_id;
+        bool m_stopRequested;
         int m_updateInterval;
-        SimulatorResourceModel m_resModel;
-        std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
         updateCompleteCallback m_callback;
         std::function<void (const int)> m_finishedCallback;
+        std::thread *m_thread;
 };
 
 typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationSP;
index 083e67f..4f3b042 100644 (file)
@@ -66,7 +66,7 @@ void SimulatorResourceServerImpl::setObservable(bool state)
 }
 
 int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type,
-        updateCompleteCallback callback)
+        int updateInterval, updateCompleteCallback callback)
 {
     if (!callback)
     {
@@ -80,11 +80,11 @@ int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type,
         throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
     }
 
-    return m_updateAutomationMgr.startResourceAutomation(this, type, -1, callback);
+    return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback);
 }
 
 int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName,
-        AutomationType type,
+        AutomationType type, int updateInterval,
         updateCompleteCallback callback)
 {
     if (!callback)
@@ -99,7 +99,7 @@ int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrNa
         throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
     }
 
-    return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, -1, callback);
+    return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, updateInterval, callback);
 }
 
 std::vector<int> SimulatorResourceServerImpl::getResourceAutomationIds()
index 471ed9c..010865c 100644 (file)
@@ -41,11 +41,11 @@ class SimulatorResourceServerImpl : public SimulatorResourceServer
 
         bool isObservable() const;
 
-        int startUpdateAutomation(AutomationType type,
+        int startUpdateAutomation(AutomationType type, int updateInterval,
                                   updateCompleteCallback callback);
 
         int startUpdateAutomation(const std::string &attrName, AutomationType type,
-                                  updateCompleteCallback callback);
+                                  int updateInterval, updateCompleteCallback callback);
 
         std::vector<int> getResourceAutomationIds();
 
index 0ceab6d..6cc820a 100644 (file)
@@ -352,6 +352,30 @@ public class SimulatorRemoteResourceTest extends TestCase
         assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
     }
 
+    /**
+     * model as null
+     */
+
+    public void testPut_N01() {
+        boolean result = true;
+        ListenerObject listenerObject = new ListenerObject();
+        PutListener putListener = new PutListener(lockObject, listenerObject);
+
+        try {
+            simulatorRemoteResource.put(null, null, putListener);
+            result = false;
+        } catch (Exception e1) {
+            result = true;
+        }
+
+        try {
+            lockObject.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+        }
+
+        assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null);
+    }
+
     public void testPost_P01()
     {
         boolean result = true;
@@ -362,7 +386,6 @@ public class SimulatorRemoteResourceTest extends TestCase
         try
         {
             model.addAttributeInt("intensity", 8);
-            //model.addAttributeString("power", "off");
 
             listenerObject = new ListenerObject();
             PostListener postListener = new PostListener(lockObject, listenerObject);
@@ -385,6 +408,33 @@ public class SimulatorRemoteResourceTest extends TestCase
         assertTrue(result && listenerObject != null && listenerObject.getRepresentation() != null && listenerObject.getuId() != null);
     }
 
+    /**
+     * Model is set to null
+     */
+
+    public void testPost_N01() {
+        boolean result = true;
+
+        lockObject = new CountDownLatch(1);
+
+        ListenerObject listenerObject = new ListenerObject();
+        PostListener postListener = new PostListener(lockObject, listenerObject);
+
+        try {
+            simulatorRemoteResource.post(null, null, postListener);
+            result = false;
+        } catch (Exception e1) {
+            result = true;
+        }
+
+        try {
+            lockObject.await(10, TimeUnit.SECONDS);
+        } catch (InterruptedException e) {
+        }
+
+        assertTrue(result && listenerObject.getRepresentation() == null && listenerObject.getuId() == null);
+    }
+
     public void testGet_P01()
     {
         boolean result = true;
@@ -398,8 +448,8 @@ public class SimulatorRemoteResourceTest extends TestCase
 
             String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0);
 
-            if(resInterface == null)
-                simulatorRemoteResource.get(resInterface, null, onGetListener);
+            if(resInterface != null)
+                simulatorRemoteResource.get(resInterface,null, onGetListener);
             else
                 result = false;
         }
@@ -462,10 +512,12 @@ public class SimulatorRemoteResourceTest extends TestCase
         {
             String resInterface = simulatorRemoteResource.getResourceInterfaces().get(0);
 
-            if(resInterface == null)
-                simulatorRemoteResource.get(resInterface, null, null);
-            else
-                result = false;
+            if(resInterface != null)
+            {
+                simulatorRemoteResource.get( resInterface,null, null);
+            }
+
+            result = false;
         }
         catch(Exception e)
         {
@@ -796,7 +848,6 @@ public class SimulatorRemoteResourceTest extends TestCase
 
         try
         {
-
             lockObject.await(100, TimeUnit.MILLISECONDS);
         }
         catch (InterruptedException e)
index 0952af1..cfbe5d2 100644 (file)
@@ -53,7 +53,6 @@ public class SimlatorResourceServerTest extends TestCase
     {
         System.loadLibrary("SimulatorManager");
         System.loadLibrary("RamlParser");
-        System.loadLibrary("YamlParser");
         System.loadLibrary("oc");
         System.loadLibrary("oc_logger");
         System.loadLibrary("octbstack");
@@ -147,13 +146,13 @@ public class SimlatorResourceServerTest extends TestCase
     {
         try
         {
-            simulatorResourceServer.addAttributeBoolean(KEY, true);
+            simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true"));
         }
         catch (Exception e)
         {
             e.printStackTrace();
         }
-        assertEquals(Boolean.parseBoolean(getValue(KEY) + ""), true);
+        assertEquals(Boolean.parseBoolean(getValue(KEY).toString() + ""), true);
     }
 
     public void testaddAttributeString_P01()
@@ -236,7 +235,7 @@ public class SimlatorResourceServerTest extends TestCase
 
         try
         {
-            simulatorResourceServer.addAttributeBoolean(KEY, true);
+            simulatorResourceServer.addAttributeBoolean(KEY, Boolean.parseBoolean("true"));
         }
         catch (Exception e)
         {
@@ -248,7 +247,7 @@ public class SimlatorResourceServerTest extends TestCase
 
         try
         {
-            simulatorResourceServer.updateAttributeBoolean(KEY, false);
+            simulatorResourceServer.updateAttributeBoolean(KEY, Boolean.parseBoolean("false"));
         }
         catch (Exception e)
         {
@@ -757,7 +756,7 @@ public class SimlatorResourceServerTest extends TestCase
 
         try
         {
-            lockObject.await(10,TimeUnit.SECONDS);
+            lockObject.await(15,TimeUnit.SECONDS);
         }
         catch (InterruptedException e)
         {
@@ -791,7 +790,7 @@ public class SimlatorResourceServerTest extends TestCase
         {
             result = false;
         }
-        assertTrue(result && id == -1);
+        assertTrue(!result && id == 0);
     }
 
     public void testStartAttributeAutomation_P01()
@@ -803,7 +802,8 @@ public class SimlatorResourceServerTest extends TestCase
         int id = 0;
         try
         {
-            id = simulatorResourceServer.startAttributeAutomation(simulatorResourceServer.getModel().getAttributes().get(0).getName(),
+            simulatorResourceServer.addAttributeInteger(KEY, 10);
+            id = simulatorResourceServer.startAttributeAutomation(KEY,
                     AutomationType.NORMAL, automationListener);
         }
         catch (Exception e)
@@ -873,14 +873,12 @@ public class SimlatorResourceServerTest extends TestCase
 
         try
         {
-            lockObject.await(10, TimeUnit.SECONDS);
+            lockObject.await(05, TimeUnit.SECONDS);
         }
         catch (InterruptedException e)
         {
         }
 
-        result = result && automationObject.getResourceURI() != null && automationObject.getAutomationId() != -1 && id != -1;
-
         try
         {
             simulatorResourceServer.stopAutomation(id);
index c46653c..7fb25db 100644 (file)
@@ -19,7 +19,6 @@ package org.oic.simulator.test;
 import java.util.concurrent.CountDownLatch;
 import junit.framework.TestCase;
 
-import org.oic.simulator.DeviceInfo;
 import org.oic.simulator.PlatformInfo;
 import org.oic.simulator.SimulatorManager;
 import org.oic.simulator.serviceprovider.SimulatorResourceServer;
@@ -38,16 +37,10 @@ public class SimulatorManagerTest extends TestCase
     private ResourceModelObject resourceModelObject;
     private ResourceModelChangeListener resourceModelChangeListener;
 
-    private DeviceInfo info;
-    private PlatformInfo platformInfo;
 
     static
     {
         System.loadLibrary("SimulatorManager");
-        System.loadLibrary("RamlParser");
-        System.loadLibrary("oc");
-        System.loadLibrary("oc_logger");
-        System.loadLibrary("octbstack");
     }
 
     @Override
@@ -212,6 +205,7 @@ public class SimulatorManagerTest extends TestCase
         SimulatorResourceServer[] simulatorResourceServers = null;
         try
         {
+            SimulatorManager.setDeviceInfo("test");
             simulatorResourceServers = SimulatorManager.createResource(configPath, count, resourceModelChangeListener);
         }
         catch (Exception e)
@@ -231,7 +225,6 @@ public class SimulatorManagerTest extends TestCase
         boolean result = false;
 
         SimulatorResourceServer[] simulatorResourceServers = null;
-
         try
         {
             simulatorResourceServers = SimulatorManager.createResource(CONFIG_PATH, count, null);
@@ -277,6 +270,19 @@ public class SimulatorManagerTest extends TestCase
         assertTrue(simulatorResourceServers == null);
     }
 
+    /**
+     * When count is set to -ve
+     */
+
+    public void testCreateResourceCount_N05()
+    {
+        int count = -10;
+
+        SimulatorResourceServer[] simulatorResourceServers = createResources(count);
+
+        assertTrue(simulatorResourceServers == null  );
+    }
+
     public void testDeleteResource_P01()
     {
         boolean result = true;
@@ -396,7 +402,42 @@ public class SimulatorManagerTest extends TestCase
      */
     public void testSetDeviceInfo_N01()
     {
-        SimulatorManager.setDeviceInfo("");
+        try
+        {
+            SimulatorManager.setDeviceInfo("");
+        }
+        catch(Exception e)
+        {
+            System.out.println("Exception hit");
+        }
+    }
+
+    /**
+    *  checking for crash
+    * pass null
+    */
+    public void testSetDeviceInfo_N02()
+    {
+        try
+        {
+            SimulatorManager.setDeviceInfo(null);
+        }
+        catch(Exception e)
+        {
+            System.out.println("Exception hit");
+        }
+    }
+
+    public void testGetDeviceInfo_N01()
+    {
+        try
+        {
+            SimulatorManager.getDeviceInfo(null);
+        }
+        catch(Exception e)
+        {
+            System.out.println(" Exception hit");
+        }
     }
 
     /**
@@ -419,4 +460,31 @@ public class SimulatorManagerTest extends TestCase
 
         SimulatorManager.setPlatformInfo(platformInfo);
     }
+
+    /**
+     * Checking for crash
+     */
+    public void testSetPlatformInfo_N01()
+    {
+        try
+        {
+            SimulatorManager.setPlatformInfo(null);
+        }
+        catch(Exception e)
+        {
+          System.out.println("Exception Hit");
+        }
+    }
+
+    public void testGetPlatformInfo_N01()
+    {
+        try
+        {
+            SimulatorManager.getPlatformInfo(null);
+        }
+        catch (Exception e)
+        {
+            System.out.println("Exception Hit");
+        }
+    }
 }
index 23448e4..2748e09 100644 (file)
@@ -203,6 +203,23 @@ public class SimulatorResourceModelTest extends TestCase
         assertTrue(result);
     }
 
+   public void testAddAttributeString_N02() {
+        String val = null;
+
+        boolean result = false;
+        try {
+
+            simulatorResourceModel.addAttributeString(KEY, val);
+
+            result = result && simulatorResourceModel.getAttribute(KEY).getValue().toString().equals(val);
+
+        } catch(Exception e) {
+            result = true;
+        }
+
+        assertTrue(result);
+    }
+
     public void testAddAttributeString_N03()
     {
         String val = "@#$$&^*^(*^&";
@@ -225,19 +242,20 @@ public class SimulatorResourceModelTest extends TestCase
     {
         boolean result = true;
 
-        boolean val = true;
+        boolean val;
 
         try
         {
+            val=Boolean.parseBoolean("true");
             simulatorResourceModel.addAttributeBoolean(KEY, val);
 
-            result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue() + "")));
+            result = result && ((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
 
-            val = false;
+            val = Boolean.parseBoolean("false");
 
             simulatorResourceModel.addAttributeBoolean(KEY, val);
 
-            result = result && !((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue() + "")));
+            result = result && !((Boolean.parseBoolean(simulatorResourceModel.getAttribute(KEY).getValue().toString()+"")));
         }
         catch (Exception e)
         {
@@ -258,7 +276,7 @@ public class SimulatorResourceModelTest extends TestCase
             result = result && (simulatorResourceModel.size() == 1);
 
             simulatorResourceModel.addAttributeString("test2", "asdf");
-            simulatorResourceModel.addAttributeBoolean("test3", true);
+            simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
             simulatorResourceModel.addAttributeDouble("test4", 22.435234);
 
             result = result && (simulatorResourceModel.size() == 4);
@@ -278,14 +296,14 @@ public class SimulatorResourceModelTest extends TestCase
         {
             simulatorResourceModel.addAttributeInt("test1", 1234);
             simulatorResourceModel.addAttributeString("test2", "asdf");
-            simulatorResourceModel.addAttributeBoolean("test3", true);
+            simulatorResourceModel.addAttributeBoolean("test3", Boolean.parseBoolean("true"));
             simulatorResourceModel.addAttributeDouble("test4", 22.435234);
 
             Map<String, ResourceAttribute> attributes = simulatorResourceModel.getAttributes();
 
             result = result && (((Integer)attributes.get("test1").getValue()) == 1234) &&
                      (((String)attributes.get("test2").getValue()).equals("asdf")) &&
-                     ((Boolean.parseBoolean(attributes.get("test3").getValue() + "")==true)) &&
+                     ((Boolean.parseBoolean(attributes.get("test3").getValue().toString() + "")==true)) &&
                      (((Double)attributes.get("test4").getValue()) == 22.435234);
         }
         catch(Exception e)
index 0f965a8..f4087cc 100755 (executable)
@@ -521,23 +521,9 @@ static void findAllResources(void *data, Evas_Object *obj, void *event_info)
     dlog_print(DLOG_INFO, LOG_TAG, "#### calling findCandidateResources ENTRY!!!!");
     std::vector<string> resourceTypes;
     resourceTypes.push_back("oic.wk.con");
-
-    if (NULL != g_groupManager)
-    {
-        g_groupManager->findCandidateResources(resourceTypes, &onFoundCandidateResource,
-                                               FINDRESOURCE_TIMEOUT);
-    }
-
-    resourceTypes.clear();
     resourceTypes.push_back("oic.wk.mnt");
-    if (NULL != g_groupManager)
-    {
-        g_groupManager->findCandidateResources(resourceTypes, &onFoundCandidateResource,
-                                               FINDRESOURCE_TIMEOUT);
-    }
-
-    resourceTypes.clear();
     resourceTypes.push_back("factoryset");
+
     if (NULL != g_groupManager)
     {
         g_groupManager->findCandidateResources(resourceTypes, &onFoundCandidateResource,
@@ -559,6 +545,15 @@ static void getConfiguration(void *data, Evas_Object *obj, void *event_info)
         return;
     }
 
+    if (NULL == g_configurationResource)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "Configuration Resource not found.");
+        string logMessage = "FIRST FIND CONFIGURATION RESOURCE <br>";
+        dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
     ConfigurationName name = "all";
     std::vector< ConfigurationName > configurations;
     configurations.push_back(name);
@@ -579,11 +574,11 @@ static void getConfiguration(void *data, Evas_Object *obj, void *event_info)
     dlog_print(DLOG_INFO, LOG_TAG, "#### getConfiguration EXIT!!!!");
 }
 
-// Updates the configuration i.e. region value to INDIA
-static void updateConfiguration(std::string newRegionValue)
+// Updates the configuration i.e. Device name to OIC Device
+static void updateConfiguration(std::string newDeviceName)
 {
     dlog_print(DLOG_INFO, LOG_TAG, "#### updateConfiguration ENTRY!!!!");
-    dlog_print(DLOG_INFO, LOG_TAG, "#### %s", newRegionValue.c_str());
+    dlog_print(DLOG_INFO, LOG_TAG, "#### %s", newDeviceName.c_str());
 
     if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
     {
@@ -595,9 +590,18 @@ static void updateConfiguration(std::string newRegionValue)
         return;
     }
 
+    if (NULL == g_configurationResource)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "Configuration Resource not found.");
+        string logMessage = "FIRST FIND CONFIGURATION RESOURCE <br>";
+        dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
     OCStackResult result;
-    ConfigurationName name = DEFAULT_REGION;
-    ConfigurationValue value = newRegionValue;
+    ConfigurationName name = DEFAULT_DEVICENAME;
+    ConfigurationValue value = newDeviceName;
 
     std::map< ConfigurationName, ConfigurationValue > configurations;
     configurations.insert(std::make_pair(name, value));
@@ -637,6 +641,15 @@ static void factoryReset(void *data, Evas_Object *obj, void *event_info)
         return;
     }
 
+    if (NULL == g_maintenanceResource)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "Maintenance Resource not found.");
+        string logMessage = "FIRST FIND MAINTENANCE RESOURCE <br>";
+        dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
     OCStackResult result;
 
     try
@@ -673,6 +686,15 @@ static void reboot(void *data, Evas_Object *obj, void *event_info)
         return;
     }
 
+    if (NULL == g_maintenanceResource)
+    {
+        dlog_print(DLOG_INFO, LOG_TAG, "Maintenance Resource not found.");
+        string logMessage = "FIRST FIND MAINTENANCE RESOURCE <br>";
+        dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+        ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateConfigLog, &logMessage);
+        return;
+    }
+
     OCStackResult result;
 
     try
@@ -779,7 +801,7 @@ popup_set_clicked_cb(void *data, Evas_Object *obj, void *event_info)
 }
 
 static void
-list_update_region_cb(void *data, Evas_Object *obj, void *event_info)
+list_update_devicename_cb(void *data, Evas_Object *obj, void *event_info)
 {
     if (NULL == g_configurationCollection || NULL == g_configurationCollection.get())
     {
@@ -800,7 +822,7 @@ list_update_region_cb(void *data, Evas_Object *obj, void *event_info)
     elm_popup_align_set(popup, ELM_NOTIFY_ALIGN_FILL, 1.0);
     eext_object_event_callback_add(popup, EEXT_CALLBACK_BACK, eext_popup_back_cb, NULL);
     evas_object_size_hint_weight_set(popup, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
-    elm_object_part_text_set(popup, "title,text", "Enter New Region Value");
+    elm_object_part_text_set(popup, "title,text", "Enter new device name to update");
 
     layout = elm_layout_add(popup);
     elm_layout_file_set(layout, ELM_DEMO_EDJ, "popup_region_text");
@@ -813,7 +835,7 @@ list_update_region_cb(void *data, Evas_Object *obj, void *event_info)
     evas_object_size_hint_weight_set(entry, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
     evas_object_size_hint_align_set(entry, EVAS_HINT_FILL, EVAS_HINT_FILL);
     eext_entry_selection_back_event_allow_set(entry, EINA_TRUE);
-    elm_object_part_text_set(entry, "elm.guide", "region value");
+    elm_object_part_text_set(entry, "elm.guide", "e.g. OIC Device");
     elm_object_part_content_set(layout, "elm.swallow.content" , entry);
 
     region_popup_fields *popup_fields;
@@ -927,8 +949,8 @@ configuration_cb(void *data, Evas_Object *obj, void *event_info)
     elm_list_item_append(list, "Find All Resources",
                          NULL, NULL, findAllResources, NULL);
     elm_list_item_append(list, "Get a Configuration Resource", NULL, NULL, getConfiguration, NULL);
-    elm_list_item_append(list, "Update Attribute (Region)", NULL, NULL,
-                         list_update_region_cb, nf);
+    elm_list_item_append(list, "Update Attribute (Device Name)", NULL, NULL,
+                         list_update_devicename_cb, nf);
     elm_list_item_append(list, "Factory Reset", NULL, NULL, factoryReset, NULL);
     elm_list_item_append(list, "Reboot", NULL, NULL, reboot, NULL);
     elm_list_item_append(list, "Get Supported Configuration Units", NULL, NULL,
index e1aef9b..1d93883 100755 (executable)
@@ -327,10 +327,16 @@ namespace OIC
 
             std::string host = getHostFromURI(oit->getUri());
 
-            tempResource = OCPlatform::constructResourceObject(host, uri, CT_ADAPTER_IP, true,
-                    oit->getResourceTypes(), m_if);
+            try
+            {
+                tempResource = OCPlatform::constructResourceObject(host, uri, CT_ADAPTER_IP, true,
+                        oit->getResourceTypes(), m_if);
 
-            p_resources.push_back(tempResource);
+                p_resources.push_back(tempResource);
+            } catch (std::exception& e)
+            {
+                std::cout << "Exception: " << e.what() << std::endl;
+            }
         }
 
         // Send GET messages to the child resources in turn.
index 6ddeebc..208ec68 100644 (file)
@@ -67,7 +67,7 @@ lib_env.AppendUnique(CPPPATH = [
                resource_path + '/include' ,
                resource_path + '/oc_logger/include',
                resource_path + '/csdk/stack/include',
-               resource_path + '/csdk/ocrandom/include',
+               resource_path + '/c_common/ocrandom/include',
                resource_path + '/csdk/logger/include'
                ])
 
index fb1d23e..27c7dd4 100755 (executable)
@@ -84,7 +84,7 @@ find $OUTDIR/objs -name "*.o" | xargs rm
 echo "Framework: Copying includes..."
 cp -r  resource/csdk/stack/include/*.h  $FRAMEWORK_BUNDLE/Headers
 cp -r  resource/csdk/ocsocket/include/*.h  $FRAMEWORK_BUNDLE/Headers
-cp -r  resource/csdk/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/c_common/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
 cp -r  resource/csdk/ocmalloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
 
 echo "Framework: Creating plist..."
index 9fa2e0a..45a0f74 100755 (executable)
@@ -85,7 +85,7 @@ find $OUTDIR/objs -name "*.o" | xargs rm
 
 echo "Framework: Copying includes..."
 cp -r  resource/csdk/stack/include/*.h  $FRAMEWORK_BUNDLE/Headers
-cp -r  resource/csdk/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
+cp -r  resource/c_common/ocrandom/include/*.h  $FRAMEWORK_BUNDLE/Headers
 cp -r  resource/csdk/ocmalloc/include/*.h  $FRAMEWORK_BUNDLE/Headers
 
 echo "Framework: Creating plist..."
index 6c6fc22..2fba7c4 100755 (executable)
@@ -130,7 +130,7 @@ cp out/tizen/*/%{build_mode}/lib*.so %{buildroot}%{_libdir}
 
 cp resource/csdk/stack/include/*.h %{buildroot}%{_includedir}
 cp resource/csdk/logger/include/*.h %{buildroot}%{_includedir}
-cp resource/csdk/ocrandom/include/*.h %{buildroot}%{_includedir}
+cp resource/c_common/ocrandom/include/*.h %{buildroot}%{_includedir}
 cp -r resource/oc_logger/include/* %{buildroot}%{_includedir}
 cp resource/include/*.h %{buildroot}%{_includedir}