Changeset for reviewing RI-CA integration changes.
authorSakthivel Samidurai <sakthivel.samidurai@intel.com>
Mon, 16 Mar 2015 22:37:32 +0000 (15:37 -0700)
committerSashi Penta <sashi.kumar.penta@intel.com>
Wed, 18 Mar 2015 20:22:00 +0000 (20:22 +0000)
--Added a single line at the end for full RI code review.
--For specific RI integration changes refer
https://gerrit.iotivity.org/gerrit/#/c/394/

Change-Id: I54e3fcf2e0c10c382d4be59d2d380eb4db5f9791
Signed-Off-By: Sudarshan Prasad <sudarshan.prasad@intel.com>
Signed-off-by: Erich Keane <erich.keane@intel.com>
Signed-off-by: Shilpa Sodani <shilpa.a.sodani@intel.com>
Signed-off-by: Sakthivel Samidurai <sakthivel.samidurai@intel.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/401
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Sashi Penta <sashi.kumar.penta@intel.com>
Tested-by: Sashi Penta <sashi.kumar.penta@intel.com>
208 files changed:
SConstruct
arduino.scons
auto_build.sh
examples/OICMiddle/Client.cpp
examples/OICMiddle/SConscript
examples/OICMiddle/makefile
examples/OICSensorBoard/SConstruct
extlibs/buildDependencies.sh
extlibs/hippomocks.scons
extra_options.scons
resource/SConscript
resource/artifact_output_locations.txt
resource/buildScript.mk
resource/csdk/README
resource/csdk/SConscript
resource/csdk/makefile
resource/csdk/ocmalloc/test/linux/makefile
resource/csdk/security/include/internal/ocsecurityinternal.h
resource/csdk/security/include/ocsecurity.h
resource/csdk/security/include/ocsecurityconfig.h
resource/csdk/security/src/ocsecurity.c
resource/csdk/stack/include/internal/occlientcb.h
resource/csdk/stack/include/internal/ocobserve.h
resource/csdk/stack/include/internal/ocresourcehandler.h
resource/csdk/stack/include/internal/ocserverrequest.h
resource/csdk/stack/include/internal/ocstackinternal.h
resource/csdk/stack/include/ocstack.h
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile
resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/makefile
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlient.h
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.h
resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.h
resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp
resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.h
resource/csdk/stack/samples/linux/secure/SConscript
resource/csdk/stack/samples/linux/secure/common.cpp
resource/csdk/stack/samples/linux/secure/common.h
resource/csdk/stack/samples/linux/secure/gen_sec_bin.cpp
resource/csdk/stack/samples/linux/secure/makefile
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.h
resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp
resource/csdk/stack/src/occlientcb.c
resource/csdk/stack/src/occollection.c
resource/csdk/stack/src/ocobserve.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/test/README
resource/csdk/stack/test/SConscript
resource/csdk/stack/test/android/README
resource/csdk/stack/test/arduino/README
resource/csdk/stack/test/arduino/makefile
resource/csdk/stack/test/arduino/ocserver.cpp
resource/csdk/stack/test/linux/makefile
resource/csdk/stack/test/linux/occlient.c
resource/csdk/stack/test/linux/ocserver.c
resource/csdk/stack/test/makefile
resource/csdk/stack/test/stacktests.cpp
resource/examples/SConscript
resource/examples/devicediscoveryclient.cpp
resource/examples/devicediscoveryserver.cpp
resource/examples/fridgeclient.cpp
resource/examples/fridgeserver.cpp
resource/examples/garageclient.cpp
resource/examples/garageserver.cpp
resource/examples/groupclient.cpp
resource/examples/groupserver.cpp
resource/examples/lightserver.cpp
resource/examples/makefile
resource/examples/presenceclient.cpp
resource/examples/presenceserver.cpp
resource/examples/roomclient.cpp
resource/examples/roomserver.cpp
resource/examples/simpleclient.cpp
resource/examples/simpleclientHQ.cpp
resource/examples/simpleclientserver.cpp
resource/examples/simpleserver.cpp
resource/examples/simpleserverHQ.cpp
resource/examples/threadingsample.cpp
resource/include/IClientWrapper.h
resource/include/InProcClientWrapper.h
resource/include/OCPlatform.h
resource/include/OCPlatform_impl.h
resource/include/OCRepresentation.h
resource/include/OCResource.h
resource/include/OCResourceResponse.h
resource/include/OCSerialization.h
resource/include/OCUtilities.h
resource/include/OutOfProcClientWrapper.h
resource/include/StringConstants.h
resource/makefile
resource/oc_logger/SConscript
resource/oc_logger/c/oc_logger.c
resource/oc_logger/examples/SConscript
resource/oc_logger/include/oc_logger_types.h
resource/oc_logger/samples/linux/makefile
resource/src/InProcServerWrapper.cpp
resource/src/OCException.cpp
resource/src/OCPlatform.cpp
resource/src/OCPlatform_impl.cpp
resource/src/OCRepresentation.cpp
resource/src/OCResource.cpp
resource/src/OCUtilities.cpp
resource/src/SConscript
resource/third_party_libs.scons
resource/unit_tests.scons
resource/unittests/ConstructResourceTest.cpp
resource/unittests/OCResourceTest.cpp
resource/unittests/README
resource/unittests/SConscript
resource/unittests/makefile
service/SConscript
service/notification-manager/NotificationManager/build/linux/Makefile
service/notification-manager/SConscript
service/notification-manager/SampleApp/linux/SConscript
service/notification-manager/build/tizen/CMakeLists.txt
service/protocol-plugin/plugin-manager/SConscript
service/protocol-plugin/plugins/SConscript
service/protocol-plugin/plugins/mqtt-fan/build/linux/Makefile
service/protocol-plugin/plugins/mqtt-light/build/linux/Makefile
service/protocol-plugin/sample-app/linux/SConscript
service/protocol-plugin/sample-app/linux/mqtt/Makefile
service/protocol-plugin/sample-app/linux/mqtt/mqttclient.cpp
service/soft-sensor-manager/SConscript
service/soft-sensor-manager/SSMCore/build/linux/Makefile
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore_JNI.cpp
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMCore_JNI.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMModelDefinition.h
service/soft-sensor-manager/SSMCore/src/SSMInterface/SSMResourceServer.cpp
service/soft-sensor-manager/SSMCore/src/SensorProcessor/ResourceFinder.cpp
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/build/makefile
service/soft-sensor-manager/SampleApp/arduino/THSensorApp1/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp
service/soft-sensor-manager/SampleApp/linux/SSMTesterApp/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp/build/Makefile
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/SConscript
service/soft-sensor-manager/SampleApp/linux/THSensorApp1/build/Makefile
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/README
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/RELEASE.txt
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/makefile_org
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/CMakeLists.txt
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/com.samsung.ssmtester.rule
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/com.samsung.ssmtester.xml
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-log.h
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-test.cpp
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-test.h
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-utils.c
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/oic-sample/src/oicapp-utils.h
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/packaging/ssm.manifest
service/soft-sensor-manager/SampleApp/tizen/SSMTesterApp/packaging/ssm.spec
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/include/DiscomfortIndexSensor.h
service/soft-sensor-manager/SoftSensorPlugin/DiscomfortIndexSensor/src/DiscomfortIndexSensor.cpp
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp
service/soft-sensor-manager/build/tizen/SampleApp/CMakeLists.txt
service/soft-sensor-manager/build/tizen/SampleApp/THSensorApp/CMakeLists.txt
service/soft-sensor-manager/build/tizen/SampleApp/THSensorApp1/CMakeLists.txt
service/things-manager/SConscript
service/things-manager/sampleapp/SConscript
service/things-manager/sampleapp/linux/configuration/SConscript
service/things-manager/sampleapp/linux/configuration/con-client.cpp
service/things-manager/sampleapp/linux/configuration/con-server.cpp
service/things-manager/sampleapp/linux/configuration/makefile
service/things-manager/sampleapp/linux/groupaction/SConscript
service/things-manager/sampleapp/linux/groupaction/groupserver.cpp
service/things-manager/sampleapp/linux/groupaction/makefile
service/things-manager/sampleapp/linux/groupsyncaction/SConscript
service/things-manager/sampleapp/linux/groupsyncaction/group.cpp
service/things-manager/sampleapp/linux/groupsyncaction/makefile
service/things-manager/sdk/build/linux/Makefile
service/things-manager/sdk/src/GroupManager.cpp
service/things-manager/sdk/src/GroupSynchronization.cpp
service/things-manager/sdk/src/GroupSynchronization.h
service/things-manager/sdk/src/ThingsConfiguration.cpp
service/things-manager/sdk/src/ThingsDiagnostics.cpp
service/third_party_libs.scons

index 3ffc00c..d58a301 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # The main build script
 #
@@ -39,3 +59,4 @@ env.PrintTargets()
 # Print bin upload command line (arduino only)
 if target_os == 'arduino':
        env.UploadHelp()
+
index fb9adfa..143b114 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
 ##
 # This script includes arduino specific config for oic-resource
 ##
index ab4ddb1..41bba84 100755 (executable)
@@ -104,3 +104,4 @@ build $1 $2 true
 build $1 $2 false
 scons resource TEST=1
 echo "===================== done ====================="
+
index 1aafde9..fbb6866 100644 (file)
@@ -1,6 +1,6 @@
 //******************************************************************
 //
-// Copyright 2014 Intel Corporation.
+// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //
@@ -19,6 +19,7 @@
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include <map>
+#include <stdexcept>
 
 #include "WrapResource.h"
 #include "Client.h"
@@ -66,14 +67,21 @@ void MiddleClient::foundOCResource(shared_ptr<OCResource> resource)
  */
 string MiddleClient::formatResourceID(std::shared_ptr<OCResource> resource)
 {
-    string host = resource->host();
-    if (host.compare(0, 7, "coap://") == 0)
-        host = host.erase(0, 7);
-    return host + resource->uri();
+    if(!resource)
+    {
+        throw invalid_argument("Invalid resource object in formatResourceID");
+    }
+
+    return resource->sid() + resource->uri();
 }
 
 void MiddleClient::addResource(WrapResource *wres)
 {
+    if(!wres)
+    {
+        throw invalid_argument("Invalid WrapResource object in addResource");
+    }
+
     string resourceID = wres->getResourceID();
     try {
         m_resourceMap[resourceID];
@@ -81,3 +89,4 @@ void MiddleClient::addResource(WrapResource *wres)
         m_resourceMap[resourceID] = wres;
     }
 }
+
index db55684..04b26fe 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # Examples build script
 ##
@@ -54,3 +74,4 @@ Alias("examples", [OICMiddle])
 env.AppendTarget('examples')
 
 
+
index 1a034bb..4a40c95 100644 (file)
@@ -1,6 +1,6 @@
 #//******************************************************************
 #//
-#// Copyright 2014 Intel Corporation.
+#// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
 #//
 #//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 #//
@@ -85,3 +85,4 @@ clean:
        rm -rf debug
        rm -rf release
 
+
index 8a4ef04..2a468aa 100644 (file)
@@ -1,9 +1,29 @@
-#This script builds edisonclient for Ubuntu and edisonserver for Yocto. 
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#This script builds edisonclient for Ubuntu and edisonserver for Yocto.
 
 #Client build for Ubuntu
 #Set IOTIVITY_ROOT to the root of oic-resource on Ubuntu.
-IOTIVITY_ROOT = '' 
-#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.               
+IOTIVITY_ROOT = ''
+#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so.
 IOTIVITY_LIBS_PATH = ''
 
 env = DefaultEnvironment()
@@ -13,7 +33,7 @@ env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap'])
 
 envClient = env.Clone()
 envClient.AppendUnique(CPPPATH = [
-                IOTIVITY_ROOT + '/resource/include', 
+                IOTIVITY_ROOT + '/resource/include',
                 IOTIVITY_ROOT + '/resource/csdk/stack/include',
                 IOTIVITY_ROOT + '/resource/oc_logger/include',
                 ])
@@ -58,6 +78,7 @@ try:
                 sdk_root + '/usr/include/iotivity/',
                 sdk_root + '/usr/include/iotivity/stack/',
                 sdk_root + '/usr/include/iotivity/oc_logger/',
-                ])                     
+                ])
 except:
     print "ERROR configuring Yocto cross-toolchain environment. This is required for building the server"
+
index 9c65248..a774338 100755 (executable)
@@ -93,3 +93,4 @@ function checkBoost {
 
 checkBoost 19 arm-linux-androideabi 4.9
 checkBoost 19 x86 4.9
+
index 9c59d82..6d5b5a4 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # 'hippomocks' script to check if Hippo Mocks Unit Test library is installed.
 # If not, get it and install it
@@ -35,3 +55,4 @@ if target_os == 'linux':
                os.rename(hippomocks_dir_src, hippomocks_dir_dest)
 
 
+
index 21739c5..ee0406a 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ######################################################################
 # This script manages extra build options
 #
@@ -31,3 +51,4 @@ if not os.path.exists(src_dir + '/extlibs/cereal'):
 *********************************************************************************
 '''
        Exit(1)
+
index d7adf7b..77af932 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # 'resource' sub-project main build script
 #
@@ -41,3 +61,4 @@ if target_os == 'linux':
 
 elif target_os == 'arduino':
        SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript')
+
index 70a2365..72b2ca5 100644 (file)
@@ -93,7 +93,7 @@ UB OCICUC:
        <oic-resource>/examples/ocicuc/client
        <oic-resource>/examples/ocicuc/monoprocess
        <oic-resource>/examples/ocicuc/server
-               
+
 
 ===============================================================================
 ====           Arduino ATMega 2560 - Release & Debug - Ethernet Shield     ====
@@ -179,3 +179,4 @@ TB Examples:
 
 
 
+
index f5be69d..7df8ce6 100644 (file)
@@ -503,3 +503,4 @@ clean:
 arduino:
        $(error "You must specify "arduinomega" or "arduinodue" when trying to\
        build arduino targets.")
+
index ac1d43e..7839acd 100644 (file)
@@ -60,3 +60,4 @@ dependencies:
 
        make deepclean
 
+
index c1b81b9..a2367f9 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # liboctbstack (share library) build script
 ##
@@ -69,7 +89,7 @@ liboctbstack_src = [
        OCTBSTACK_SRC + 'occlientcb.c',
        OCTBSTACK_SRC + 'ocresource.c',
        OCTBSTACK_SRC + 'ocobserve.c',
-    OCTBSTACK_SRC + 'ocserverrequest.c',
+       OCTBSTACK_SRC + 'ocserverrequest.c',
        OCTBSTACK_SRC + 'occollection.c',
        OCTBSTACK_SRC + 'oicgroup.c',
        'security/src/ocsecurity.c',
@@ -83,3 +103,4 @@ else:
        liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src)
 
 liboctbstack_env.InstallTarget(liboctbstack, 'liboctbstack')
+
index 24363bb..31cc697 100644 (file)
@@ -222,3 +222,4 @@ legacy_deepclean:
        rm -rf $(OBJ_DIR)
        rm -rf release
        rm -rf debug
+
index fad0401..5beaea8 100644 (file)
@@ -96,3 +96,4 @@ clean: legacy_clean
 
 legacy_clean:
        rm -f *.o $(PROGRAMS)
+
index ca8fe71..5f5b2d1 100644 (file)
@@ -63,3 +63,4 @@ void GetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo);
 void DeinitOCSecurityInfo();
 
 #endif //OC_SECURITY_INTERNAL_H
+
index eceaabb..1d1b3e4 100644 (file)
@@ -47,3 +47,4 @@ OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData,
 #endif // __cplusplus
 
 #endif //OC_SECURITY_H
+
index e8db4cc..cf2fd74 100644 (file)
@@ -141,7 +141,7 @@ OCStackResult ValidateBlobTypePSK(const OCSecBlob *secBlob)
     OCDtlsPskCredsBlob *pskCredsBlob;
     uint16_t validLen;
 
-    if(secBlob->len == 0)
+    if(!secBlob || secBlob->len == 0)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -253,3 +253,4 @@ OCStackResult OCSecSetConfigData(const OCSecConfigData *cfgData,
 }
 
 
+
index 2bc2355..b3f100f 100644 (file)
 #include <ocresource.h>
 #include "cacommon.h"
 
-typedef struct OCPresence {
+typedef struct OCPresence
+{
     // This is the TTL associated with presence
     uint32_t TTL;
     uint32_t * timeOut;
     uint32_t TTLlevel;
-}OCPresence;
+} OCPresence;
 
-typedef struct OCMulticastNode {
-    unsigned char * uri;
+typedef struct OCMulticastNode
+{
+    char * uri;
     uint32_t nonce;
     struct OCMulticastNode * next;
 } OCMulticastNode;
 
-extern OCMulticastNode * mcPresenceNodes;
-
 typedef struct ClientCB {
     // callback method defined in application address space
     OCClientResponseHandler callBack;
@@ -59,7 +59,7 @@ typedef struct ClientCB {
     // This is the sequence identifier the server applies to the invocation tied to 'handle'.
     uint32_t sequenceNumber;
     // This is the request uri associated with the call back
-    unsigned char * requestUri;
+    char * requestUri;
     // Struct to hold TTL info for presence
     #ifdef WITH_PRESENCE
     OCPresence * presence;
@@ -71,19 +71,20 @@ typedef struct ClientCB {
 
 extern struct ClientCB *cbList;
 
-//-- AddClientCB -----------------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to add a client callback method in cbList.
  *
  * @param[out] clientCB
  *              The resulting node from making this call. Null if out of memory.
- * @param[in] cb
+ * @param[in] cbData
  *              address to client callback function.
  * @param[in] token
  *              identifier for OTA CoAP comms.
  * @param[in] handle
  *              Masked in the public API as an 'invocation handle' - Used for callback management.
+ * @param[in] method
+ *              OCMethod via which this client callback is expected to operate
  * @param[in] requestUri
  *              the resource uri of the request.
  * @param[in] resourceType
@@ -91,15 +92,13 @@ extern struct ClientCB *cbList;
  *
  * @brief If the handle you're looking for does not exist, the stack will reply with a RST message.
  *
- * @retval OC_STACK_OK for Success, otherwise some error value
+ * @return OC_STACK_OK for Success, otherwise some error value
  */
-//------------------------------------------------------------------------
 OCStackResult
 AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
              CAToken_t * token, OCDoHandle *handle, OCMethod method,
-             unsigned char * requestUri, unsigned char * resourceTypeName);
+             char * requestUri, char * resourceTypeName);
 
-//-- DeleteClientCB -----------------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to remove a callback node from cbList.
@@ -107,14 +106,12 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
  * @param[in] cbNode
  *              address to client callback node.
  */
-//------------------------------------------------------------------------
 void DeleteClientCB(ClientCB *cbNode);
 
 
-//-- GetClientCB ---------------------------------------------------------
 /** @ingroup ocstack
  *
- * This method is used to search a cb node in cbList.
+ * This method is used to search and retrieve a cb node in cbList.
  *
  * @param[in] token
  *              token to search for.
@@ -123,18 +120,19 @@ void DeleteClientCB(ClientCB *cbNode);
  * @param[in] requestUri
  *              Uri to search for.
  *
- * @brief You can search by token OR by handle. Not both.
+ * @brief You can search by token OR by handle, but not both.
  *
- * @retval address of the node if found, otherwise NULL
+ * @return address of the node if found, otherwise NULL
  */
-//------------------------------------------------------------------------
-ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned char * requestUri);
+ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const char * requestUri);
 
 /**
- * Inserts a new resource type filter into this clientCB node.
+ * Inserts a new resource type filter into this cb node.
  *
- * @param cbNode - the node to add the new resourceType filter to
- * @param resourceTypeName - the value to create the new resourceType filter from
+ * @param[in] cbNode
+ *              the node to add the new resourceType filter to
+ * @param[in] resourceTypeName
+ *              the value to create the new resourceType filter from
  *
  * @return
  *      OC_STACK_OK on success
@@ -145,16 +143,13 @@ ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned
 OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName);
 #endif // WITH_PRESENCE
 
-//-- DeleteClientCBList --------------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to clear the cbList.
  *
  */
-//------------------------------------------------------------------------
 void DeleteClientCBList();
 
-//-- FindAndDeleteClientCB -----------------------------------------------
 /** @ingroup ocstack
  *
  * This method is used to verify the presence of a cb node in cbList
@@ -163,7 +158,6 @@ void DeleteClientCBList();
  * @param[in] cbNode
  *              address to client callback node.
  */
-//------------------------------------------------------------------------
 void FindAndDeleteClientCB(ClientCB * cbNode);
 
 /** @ingroup ocstack
@@ -177,7 +171,7 @@ void FindAndDeleteClientCB(ClientCB * cbNode);
  *              The resulting node from making this call. Null if doesn't exist.
  */
 //------------------------------------------------------------------------
-OCMulticastNode* GetMCPresenceNode(const unsigned char * uri);
+OCMulticastNode* GetMCPresenceNode(const char * uri);
 
 /** @ingroup ocstack
  *
@@ -193,6 +187,7 @@ OCMulticastNode* GetMCPresenceNode(const unsigned char * uri);
  * @return OC_STACK_OK for Success, otherwise some error value
  */
 //------------------------------------------------------------------------
-OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce);
+OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce);
 
 #endif //OC_CLIENT_CB
+
index 9125b9f..28af694 100644 (file)
 #ifndef OC_OBSERVE_H
 #define OC_OBSERVE_H
 
-/* In CoAP sequence number is a 24 bit field */
+/* Sequence number is a 24 bit field */
 #define MAX_SEQUENCE_NUMBER              (0xFFFFFF)
 
 #define MAX_OBSERVER_FAILED_COMM         (2)
 #define MAX_OBSERVER_NON_COUNT           (3)
 
 /* This information is stored for each registerd observer */
-typedef struct ResourceObserver {
+typedef struct ResourceObserver
+{
     // Observation Identifier for request
     OCObservationId observeId;
     // URI of observed resource
-    unsigned char *resUri;
+    char *resUri;
     // Query
-    unsigned char *query;
+    char *query;
     //token for the observe request
     CAToken_t token;
     // Resource handle
@@ -65,7 +66,7 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 #endif
 OCStackResult SendListObserverNotification (OCResource * resource,
         OCObservationId  *obsIdList, uint8_t numberOfIds,
-        unsigned char *notificationJSONPayload, uint32_t maxAge,
+        const char *notificationJSONPayload, uint32_t maxAge,
         OCQualityOfService qos);
 
 void DeleteObserverList();
@@ -78,10 +79,11 @@ OCStackResult AddObserver (const char         *resUri,
                            CAToken_t          *token,
                            OCResource         *resHandle,
                            OCQualityOfService qos,
-                           CAAddress_t          *addressInfo,
+                           const CAAddress_t  *addressInfo,
                            CAConnectivityType_t connectivityType);
 
 OCStackResult DeleteObserverUsingToken (CAToken_t * token);
+
 ResourceObserver* GetObserverUsingToken (const CAToken_t * token);
 
 ResourceObserver* GetObserverUsingId (const OCObservationId observeId);
@@ -97,3 +99,4 @@ GetObserveHeaderOption (uint32_t * observationOption,
                         uint8_t * numOptions);
 
 #endif //OC_OBSERVE_H
+
index fef013d..7a2859e 100644 (file)
@@ -28,6 +28,8 @@
 #define OC_RSRVD_OC                     "oc"
 #define OC_RSRVD_PAYLOAD                "payload"
 #define OC_RSRVD_HREF                   "href"
+#define OC_RSRVD_REPRESENTATION         "rep"
+#define OC_RSRVD_CONTENT_TYPE           "ct"
 #define OC_RSRVD_RESOURCE_TYPE          "rt"
 #define OC_RSRVD_RESOURCE_TYPE_PRESENCE "core.presence"
 #define OC_RSRVD_INTERFACE              "if"
 #define OC_RSRVD_INTERFACE_BATCH        "oc.mi.b"
 #define OC_RSRVD_INTERFACE_GROUP        "oc.mi.grp"
 
+#define OC_RSRVD_MFG_DATE               "mndt"
+#define OC_RSRVD_FW_VERSION             "mnfv"
+#define OC_RSRVD_HOST_NAME              "hn"
+#define OC_RSRVD_MFG_NAME               "mnmn"
+#define OC_RSRVD_MFG_URL                "mnml"
+#define OC_RSRVD_MODEL_NUM              "mnmo"
+#define OC_RSRVD_PLATFORM_VERSION       "mnpv"
+#define OC_RSRVD_SUPPORT_URL            "mnsl"
+#define OC_RSRVD_VERSION                "icv"
+
 
 #define OC_RSRVD_OBSERVABLE             "obs"
 #define OC_RSRVD_SECURE                 "sec"
@@ -54,7 +66,8 @@
 #define OC_RESOURCE_OBSERVABLE   1
 #define OC_RESOURCE_SECURE       1
 
-typedef enum {
+typedef enum
+{
     STACK_RES_DISCOVERY_NOFILTER = 0,
     STACK_RES_DISCOVERY_IF_FILTER,
     STACK_RES_DISCOVERY_RT_FILTER,
@@ -62,7 +75,8 @@ typedef enum {
     STACK_DEVICE_DISCOVERY_DN_FILTER
 } StackQueryTypes;
 
-typedef enum {
+typedef enum
+{
     OC_RESOURCE_VIRTUAL = 0,
     OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER,
     OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER,
@@ -98,3 +112,4 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
 OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult);
 
 #endif //OC_RESOURCEHANDLER_H
+
index beb63aa..8c28fe7 100644 (file)
@@ -31,13 +31,14 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse);
 OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse);
 
 // following structure will be created in occoap and passed up the stack on the server side
-typedef struct OCServerRequest {
+typedef struct OCServerRequest
+{
     // the REST method retrieved from received request PDU
     OCMethod method;
     // resourceUrl will be filled in occoap using the path options in received request PDU
-    unsigned char resourceUrl[MAX_URI_LENGTH];
+    char resourceUrl[MAX_URI_LENGTH];
     // resource query send by client
-    unsigned char query[MAX_QUERY_LENGTH];
+    char query[MAX_QUERY_LENGTH];
 
     // qos is indicating if the request is CON or NON
     OCQualityOfService qos;
@@ -66,14 +67,14 @@ typedef struct OCServerRequest {
     uint8_t slowFlag;
     uint8_t notificationFlag;
     // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char reqJSONPayload[1];
+    char reqJSONPayload[1];
 } OCServerRequest;
 
 // following structure will be created in ocstack to aggregate responses (in future: for block transfer)
 typedef struct OCServerResponse {
     struct OCServerResponse * next;
     // this is the pointer to server payload data to be transferred
-    unsigned char *payload;
+    char *payload;
     uint16_t remainingPayloadSize;
     OCRequestHandle requestHandle;
 } OCServerResponse;
@@ -87,17 +88,17 @@ OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
         uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
         uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
-        OCQualityOfService qos, unsigned char * query,
+        OCQualityOfService qos, char * query,
         OCHeaderOption * rcvdVendorSpecificHeaderOptions,
-        unsigned char * reqJSONPayload, CAToken_t * requestToken,
-        unsigned char * resourceUrl, size_t reqTotalSize,
+        char * reqJSONPayload, CAToken_t * requestToken,
+        char * resourceUrl, size_t reqTotalSize,
         CAAddress_t *addressInfo, CAConnectivityType_t connectivityType);
 
 OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle);
 
 // Internal function to create OCEntityHandlerRequest at the server from a received coap pdu
 OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request,
-        OCMethod method, OCResourceHandle resource, unsigned char * queryBuf, unsigned char * bufReqPayload,
+        OCMethod method, OCResourceHandle resource, char * queryBuf, char * bufReqPayload,
         uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction,
         OCObservationId observeID);
 
@@ -110,3 +111,4 @@ void FindAndDeleteServerResponse(OCServerResponse * serverResponse);
 void DeleteServerResponse(OCServerResponse * serverResponse);
 
 #endif //OC_SERVER_REQUEST_H
+
index 80e784f..ef73531 100644 (file)
@@ -54,7 +54,8 @@ extern OCDeviceEntityHandler defaultDeviceHandler;
 #define OC_COAP_SCHEME "coap://"
 #define OC_OFFSET_SEQUENCE_NUMBER (4) // the first outgoing sequence number will be 5
 
-typedef struct {
+typedef struct
+{
     // Observe option field
     uint32_t option;
     // IP address & port of client registered for observe
@@ -67,17 +68,18 @@ typedef struct {
 } OCObserveReq;
 
 // following structure will be created in occoap and passed up the stack on the server side
-typedef struct {
+typedef struct
+{
     // Observe option field
     uint32_t observationOption;
     // the REST method retrieved from received request PDU
     OCMethod method;
     // resourceUrl will be filled in occoap using the path options in received request PDU
-    unsigned char resourceUrl[MAX_URI_LENGTH];
+    char resourceUrl[MAX_URI_LENGTH];
     // resource query send by client
-    unsigned char query[MAX_QUERY_LENGTH];
+    char query[MAX_QUERY_LENGTH];
     // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char reqJSONPayload[MAX_REQUEST_LENGTH];
+    char reqJSONPayload[MAX_REQUEST_LENGTH];
     // qos is indicating if the request is CON or NON
     OCQualityOfService qos;
     // An array of the received vendor specific header options
@@ -130,28 +132,29 @@ typedef struct
     uint8_t slowFlag;
     uint8_t notificationFlag;
     // this is the pointer to server payload data to be transferred
-    unsigned char *payload;
+    char *payload;
     // size of server payload data.  Don't rely on null terminated data for size
     uint16_t payloadSize;
     // An array of the vendor specific header options the entity handler wishes to use in response
     uint8_t numSendVendorSpecificHeaderOptions;
     OCHeaderOption *sendVendorSpecificHeaderOptions;
     // URI of new resource that entity handler might create
-    unsigned char * resourceUri;
+    char * resourceUri;
 } OCServerProtocolResponse;
 
 // following structure will be created in occoap and passed up the stack on the client side
-typedef struct {
+typedef struct
+{
     // handle is retrieved by comparing the token-handle pair in the PDU.
     ClientCB * cbNode;
     // This is how long this response is valid for (in seconds).
     uint32_t maxAge;
     // This is the Uri of the resource. (ex. "coap://192.168.1.1/a/led")
-    unsigned char * fullUri;
+    char * fullUri;
     // This is the relative Uri of the resource. (ex. "/a/led")
-    unsigned char * rcvdUri;
+    char * rcvdUri;
     // This is the received payload.
-    unsigned char * bufRes;
+    char * bufRes;
 
     // This is the token received OTA.
     CAToken_t * rcvdToken;
@@ -175,7 +178,7 @@ OCStackResult HandleStackResponses(OCResponse * response);
 OCStackResult SendPresenceNotification(OCResourceType *resourceType);
 OCStackResult SendStopNotification();
 #endif // WITH_PRESENCE
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
+int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port);
 
 OCStackResult BindResourceInterfaceToResource(OCResource* resource,
                                             const char *resourceInterfaceName);
@@ -211,3 +214,4 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
 #endif // __cplusplus
 
 #endif /* OCSTACKINTERNAL_H_ */
+
index 2507d10..eec9c29 100644 (file)
@@ -40,7 +40,6 @@ extern "C" {
 #define OC_MULTICAST_PREFIX                  "224.0.1.187:5683"
 #define OC_MULTICAST_IP                      "224.0.1.187"
 
-#define USE_RANDOM_PORT (0)
 #ifdef WITH_PRESENCE
 #define OC_DEFAULT_PRESENCE_TTL (60)
 #define OC_PRESENCE_URI                      "/oc/presence"
@@ -63,7 +62,7 @@ typedef struct OCDevAddr
 {
     uint32_t     size;                    /**< length of the address stored in addr field. */
     uint8_t      addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
-}OCDevAddr;
+} OCDevAddr;
 
 /**
  * OC Virtual resources supported by every OC device
@@ -82,7 +81,8 @@ typedef enum
 /**
  * Standard RESTful HTTP Methods
  */
-typedef enum {
+typedef enum
+{
     OC_REST_NOMETHOD    = 0,
     OC_REST_GET         = (1 << 0),     // Read
     OC_REST_PUT         = (1 << 1),     // Write
@@ -103,17 +103,18 @@ typedef enum {
 /**
  * Host Mode of Operation
  */
-typedef enum {
+typedef enum
+{
     OC_CLIENT = 0,
     OC_SERVER,
     OC_CLIENT_SERVER
 } OCMode;
 
-extern OCMode myStackMode;
 /**
  * Quality of Service
  */
-typedef enum {
+typedef enum
+{
     OC_LOW_QOS = 0,
     OC_MEDIUM_QOS,
     OC_HIGH_QOS,
@@ -133,7 +134,8 @@ typedef enum {
  *                   requests from clients.
  * OC_SECURE       - When this bit is set, the resource is a secure resource.
  */
-typedef enum {
+typedef enum
+{
     OC_ACTIVE       = (1 << 0),
     OC_DISCOVERABLE = (1 << 1),
     OC_OBSERVABLE   = (1 << 2),
@@ -144,7 +146,8 @@ typedef enum {
 /**
  * Transport Protocol IDs
  */
-typedef enum {
+typedef enum
+{
     OC_INVALID_ID   = (1 << 0),
     OC_COAP_ID      = (1 << 1)
 } OCTransportProtocolID;
@@ -152,7 +155,8 @@ typedef enum {
 /**
  * Adaptor types
  */
-typedef enum {
+typedef enum
+{
     OC_ETHERNET = 0,
     OC_WIFI,
     OC_EDR,
@@ -163,7 +167,8 @@ typedef enum {
 /**
  * Declares Stack Results & Errors
  */
-typedef enum {
+typedef enum
+{
     /* Success status code - START HERE */
     OC_STACK_OK = 0,
     OC_STACK_RESOURCE_CREATED,
@@ -230,13 +235,15 @@ typedef uint8_t OCObservationId;
 /**
  * Action associated with observation
  */
-typedef enum {
+typedef enum
+{
     OC_OBSERVE_REGISTER = 0,
     OC_OBSERVE_DEREGISTER = 1,
     OC_OBSERVE_NO_OPTION = 2
 } OCObserveAction;
 
-typedef struct {
+typedef struct
+{
     // Action associated with observation request
     OCObserveAction action;
     // Identifier for observation being registered/deregistered
@@ -246,7 +253,8 @@ typedef struct {
 /**
  * Possible returned values from entity handler
  */
-typedef enum {
+typedef enum
+{
     OC_EH_OK = 0,
     OC_EH_ERROR,
     OC_EH_RESOURCE_CREATED,
@@ -258,7 +266,8 @@ typedef enum {
 // following structure will be used to define the vendor specific header options to be included
 // in communication packets
 
-typedef struct OCHeaderOption {
+typedef struct OCHeaderOption
+{
     // The protocol ID this option applies to
     OCTransportProtocolID protocolID;
     // The header option ID which will be added to communication packets
@@ -270,17 +279,20 @@ typedef struct OCHeaderOption {
 } OCHeaderOption;
 
 /**
- * Incoming requests handled by the server. Requests are passed in as a parameter to the @ref OCEntityHandler callback API.
- * @brief The @ref OCEntityHandler callback API must be implemented in the application in order to receive these requests.
+ * Incoming requests handled by the server. Requests are passed in as a parameter to the
+ * @ref OCEntityHandler callback API.
+ * @brief The @ref OCEntityHandler callback API must be implemented in the application in order
+ * to receive these requests.
  */
-typedef struct {
+typedef struct
+{
     // Associated resource
     OCResourceHandle resource;
     OCRequestHandle requestHandle;
     // the REST method retrieved from received request PDU
     OCMethod method;
     // resource query send by client
-    unsigned char * query;
+    char * query;
     // Information associated with observation - valid only when OCEntityHandler
     // flag includes OC_OBSERVE_FLAG
     OCObservationInfo obsInfo;
@@ -288,13 +300,14 @@ typedef struct {
     uint8_t numRcvdVendorSpecificHeaderOptions;
     OCHeaderOption * rcvdVendorSpecificHeaderOptions;
     // reqJSON is retrieved from the payload of the received request PDU
-    unsigned char * reqJSONPayload;
-}OCEntityHandlerRequest;
+    char * reqJSONPayload;
+} OCEntityHandlerRequest;
 
 /**
  * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
  */
-typedef struct {
+typedef struct
+{
     // Address of remote server
     OCDevAddr * addr;
     // Indicates adaptor type on which the response was received
@@ -304,11 +317,11 @@ typedef struct {
     // If associated with observe, this will represent the sequence of notifications from server.
     uint32_t sequenceNumber;
     // resJSONPayload is retrieved from the payload of the received request PDU
-    unsigned  const char * resJSONPayload;
+    const char * resJSONPayload;
     // An array of the received vendor specific header options
     uint8_t numRcvdVendorSpecificHeaderOptions;
     OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
-}OCClientResponse;
+} OCClientResponse;
 
 /**
  * Following structure describes the device properties. All non-Null properties will be included
@@ -342,26 +355,28 @@ typedef struct
     // Allow the entity handler to pass a result with the response
     OCEntityHandlerResult  ehResult;
     // this is the pointer to server payload data to be transferred
-    unsigned char *payload;
+    char *payload;
     // size of server payload data.  I don't think we should rely on null terminated data for size
     uint16_t payloadSize;
     // An array of the vendor specific header options the entity handler wishes to use in response
     uint8_t numSendVendorSpecificHeaderOptions;
     OCHeaderOption sendVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS];
     // URI of new resource that entity handler might create
-    unsigned char resourceUri[MAX_URI_LENGTH];
+    char resourceUri[MAX_URI_LENGTH];
     // Server sets to true for persistent response buffer, false for non-persistent response buffer
     uint8_t persistentBufferFlag;
 } OCEntityHandlerResponse;
 
-typedef enum {
+typedef enum
+{
     OC_INIT_FLAG    = (1 << 0),
     OC_REQUEST_FLAG = (1 << 1),
     OC_OBSERVE_FLAG = (1 << 2)
 } OCEntityHandlerFlag; //entity_handler_flag_t ;
 
 // possible returned values from client application
-typedef enum {
+typedef enum
+{
     OC_STACK_DELETE_TRANSACTION = 0,
     OC_STACK_KEEP_TRANSACTION
 } OCStackApplicationResult;
@@ -385,7 +400,8 @@ typedef void (* OCClientContextDeleter)(void *context);
 /*
  * This info is passed from application to OC Stack when initiating a request to Server
  */
-typedef struct {
+typedef struct
+{
     void *context;
     OCClientResponseHandler cb;
     OCClientContextDeleter cd;
@@ -468,7 +484,7 @@ OCStackResult OCProcess();
  *                             the well-known multicast IP address, the qos will be forced to
  *                             OC_LOW_QOS
  *                             since it is impractical to send other QOS levels on such addresses.
- * @param clientApplicationCB- asynchronous callback function that is invoked
+ * @param cbData             - asynchronous callback function that is invoked
  *                             by the stack when discovery or resource interaction is complete
  * @param options            - The address of an array containing the vendor specific
  *                             header options to be sent with the request
@@ -732,10 +748,10 @@ const char *OCGetResourceUri(OCResourceHandle handle);
  *
  * @param handle - handle of resource
  * @return
- *    property bitmap - if resource found
- *    NULL - resource not found
+ *    OCResourceProperty Bitmask
+ *    -1 if resource is not found
  */
-uint8_t OCGetResourceProperties(OCResourceHandle handle);
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle);
 
 /**
  * Get the number of resource types of the resource.
@@ -765,14 +781,15 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index);
  * Get the number of resource interfaces of the resource.
  *
  * @param handle - handle of resource
- * @param numResources - pointer to count variable
+ * @param numResourceInterfaces - pointer to count variable
  *
  * @return
  *     OC_STACK_OK    - no errors
  *     OC_STACK_ERROR - stack process error
 
  */
-OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, uint8_t *numResourceInterfaces);
+OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
+        uint8_t *numResourceInterfaces);
 
 /**
  * Get name of resource interface of the resource.
@@ -808,7 +825,8 @@ uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t in
  *    handle to contained resource - if resource found
  *    NULL - resource not found
  */
-OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, uint8_t index);
+OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
+        uint8_t index);
 
 /**
  * Get the entity handler for a resource.
@@ -827,6 +845,7 @@ OCEntityHandler OCGetResourceHandler(OCResourceHandle handle);
  * if the query is valid after the resource representation has changed.
  *
  * @param handle - handle of resource
+ * @param qos    - desired quality of service for the observation notifications
  *
  * @return
  *     OC_STACK_OK    - no errors
@@ -857,7 +876,7 @@ OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                             OCObservationId  *obsIdList,
                             uint8_t          numberOfIds,
-                            unsigned char    *notificationJSONPayload,
+                            const char    *notificationJSONPayload,
                             OCQualityOfService qos);
 
 
@@ -926,3 +945,5 @@ int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port);
 #endif // __cplusplus
 
 #endif /* OCSTACK_H_ */
+
+
index edf9076..9da4c16 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 Import('env')
 
 arduino_simplecs_env = env.Clone()
index 1591210..2b08e12 100644 (file)
@@ -189,10 +189,11 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle
             response.requestHandle = entityHandlerRequest->requestHandle;
             response.resourceHandle = entityHandlerRequest->resource;
             response.ehResult = ehRet;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             response.numSendVendorSpecificHeaderOptions = 0;
-            memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+            memset(response.sendVendorSpecificHeaderOptions, 0,
+                    sizeof response.sendVendorSpecificHeaderOptions);
             memset(response.resourceUri, 0, sizeof response.resourceUri);
             // Indicate that response is NOT in a persistent buffer
             response.persistentBufferFlag = 0;
@@ -228,7 +229,8 @@ void *ChangeLightRepresentation (void *param)
     (void)param;
     OCStackResult result = OC_STACK_ERROR;
     modCounter += 1;
-    if(modCounter % 10 == 0)  // Matching the timing that the Linux Sample Server App uses for the same functionality.
+    // Matching the timing that the Linux Sample Server App uses for the same functionality.
+    if(modCounter % 10 == 0)
     {
         Light.power += 5;
         if (gLightUnderObservation)
@@ -274,7 +276,7 @@ void setup()
 void loop()
 {
     // This artificial delay is kept here to avoid endless spinning
-    // of Arduino microcontroller. Modify it as per specfic application needs.
+    // of Arduino microcontroller. Modify it as per specific application needs.
     delay(2000);
 
     // This call displays the amount of free SRAM available on Arduino
@@ -339,3 +341,4 @@ const char *getResult(OCStackResult result) {
         return "UNKNOWN";
     }
 }
+
index f02c19f..a9b3aac 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 Import('env')
 
@@ -45,3 +64,4 @@ Alias("samples", [ocserver, occlient,
 
 env.AppendTarget('samples')
 
+
index b4e20ba..9dce85f 100644 (file)
@@ -72,7 +72,7 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7> -c <0|1>");
+    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1..17> -c <0|1>");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
     OC_LOG(INFO, TAG, "-t 1  :  Discover Resources");
@@ -153,6 +153,10 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response",
                 clientResponse->resJSONPayload);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "putReqCB received Null clientResponse");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -169,6 +173,10 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientRespons
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
                 clientResponse->resJSONPayload);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "postReqCB received Null clientResponse");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -186,6 +194,10 @@ OCStackApplicationResult deleteReqCB(void *ctx,
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response",
                 clientResponse->resJSONPayload);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "deleteReqCB received Null clientResponse");
+    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -193,9 +205,10 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 {
     if(clientResponse == NULL)
     {
-        OC_LOG(INFO, TAG, "The clientResponse is NULL");
+        OC_LOG(INFO, TAG, "getReqCB received NULL clientResponse");
         return   OC_STACK_DELETE_TRANSACTION;
     }
+
     if(ctx == (void*)DEFAULT_CONTEXT_VALUE)
     {
         OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
@@ -274,6 +287,10 @@ OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "obsReqCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 #ifdef WITH_PRESENCE
@@ -302,6 +319,10 @@ OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientRespon
             return OC_STACK_DELETE_TRANSACTION;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "presenceCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 #endif
@@ -341,7 +362,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 InitGetRequest(OC_LOW_QOS, 0);
                 break;
             case TEST_PUT_REQ_NON:
-                InitPutRequest();
+                InitPutRequest(OC_LOW_QOS);
                 break;
             case TEST_POST_REQ_NON:
                 InitPostRequest(OC_LOW_QOS);
@@ -354,7 +375,7 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 InitObserveRequest(OC_LOW_QOS);
                 break;
             case TEST_GET_UNAVAILABLE_RES_REQ_NON:
-                InitGetRequestToUnavailableResource();
+                InitGetRequestToUnavailableResource(OC_LOW_QOS);
                 break;
             case TEST_GET_REQ_CON:
                 InitGetRequest(OC_HIGH_QOS, 0);
@@ -379,13 +400,17 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
                 InitGetRequest(OC_LOW_QOS, 1);
                 break;
             case TEST_DISCOVER_DEV_REQ:
-                InitDeviceDiscovery();
+                InitDeviceDiscovery(OC_LOW_QOS);
                 break;
             default:
                 PrintUsage();
                 break;
         }
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "discoveryReqCB received Null clientResponse");
+    }
     return OC_STACK_KEEP_TRANSACTION;
 }
 
@@ -403,6 +428,10 @@ OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle,
         fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload);
         fflush(stderr);
     }
+    else
+    {
+        OC_LOG_V(INFO, TAG, "DeviceDiscoveryReqCB received Null clientResponse");
+    }
 
     return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION;
 }
@@ -441,12 +470,13 @@ int InitPresence()
 }
 #endif
 
-int InitGetRequestToUnavailableResource()
+int InitGetRequestToUnavailableResource(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource";
-    return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+            getReqCB, NULL, 0));
 }
 
 int InitObserveRequest(OCQualityOfService qos)
@@ -458,12 +488,13 @@ int InitObserveRequest(OCQualityOfService qos)
             OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0));
 }
 
-int InitPutRequest()
+int InitPutRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_PUT, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS,
+            putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
@@ -591,7 +622,7 @@ int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptio
     }
 }
 
-int InitDeviceDiscovery()
+int InitDeviceDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -614,12 +645,12 @@ int InitDeviceDiscovery()
     if(UNICAST_DISCOVERY)
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
     else
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
 
     if (ret != OC_STACK_OK)
@@ -630,7 +661,7 @@ int InitDeviceDiscovery()
     return ret;
 }
 
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -652,12 +683,12 @@ int InitDiscovery()
     if(UNICAST_DISCOVERY)
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_CONNTYPE,
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
     else
     {
         ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, (OC_ALL),
-                OC_LOW_QOS, &cbData, NULL, 0);
+                (qos == OC_HIGH_QOS) ? OC_HIGH_QOS : OC_LOW_QOS, &cbData, NULL, 0);
     }
     if (ret != OC_STACK_OK)
     {
@@ -719,11 +750,11 @@ int main(int argc, char* argv[])
 
     if(UNICAST_DISCOVERY  == 0  && TEST_CASE == TEST_DISCOVER_DEV_REQ)
     {
-        InitDeviceDiscovery();
+        InitDeviceDiscovery(OC_LOW_QOS);
     }
     else
     {
-        InitDiscovery();
+        InitDiscovery(OC_LOW_QOS);
     }
 
     // Break from loop with Ctrl+C
@@ -825,3 +856,4 @@ void parseClientResponse(OCClientResponse * clientResponse)
     coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
+
index b1fe562..c37ac29 100644 (file)
@@ -87,15 +87,15 @@ std::string getQueryStrForGetPut(OCClientResponse * clientResponse);
 /* Following are initialization functions for GET, Observe, PUT
  * POST, Delete & Discovery operations
  */
-int InitGetRequestToUnavailableResource();
+int InitGetRequestToUnavailableResource(OCQualityOfService qos);
 int InitObserveRequest(OCQualityOfService qos);
-int InitPutRequest();
+int InitPutRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions);
 int InitPostRequest(OCQualityOfService qos);
 int InitDeleteRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos);
-int InitDeviceDiscovery();
-int InitDiscovery();
+int InitDeviceDiscovery(OCQualityOfService qos);
+int InitDiscovery(OCQualityOfService qos);
 
 /* Function to retrieve ip address, port no. of the server
  *  and query for the operations to be performed.
@@ -138,3 +138,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
 
 #endif
+
index 58c9df2..e126035 100644 (file)
@@ -342,7 +342,7 @@ int InitDiscovery()
     OCStackResult ret;
     OCCallbackData cbData;
     /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[64] = {};
     if (UNICAST_DISCOVERY)
     {
         char ipv4addr[IPV4_ADDR_SIZE];
@@ -427,7 +427,7 @@ const char * getPort(const OCClientResponse * clientResponse)
     return port;
 }
 
-int parseJSON(unsigned  const char * resJSONPayload, char ** sid_c,
+int parseJSON(const char * resJSONPayload, char ** sid_c,
               char *** uri_c, int * totalRes)
 {
     cJSON * root = NULL;
@@ -739,3 +739,4 @@ int main(int argc, char* argv[])
     return 0;
 }
 
+
index 2a33c49..c9d0dc9 100644 (file)
@@ -156,3 +156,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse);
 void StripNewLineChar(char* str);
 #endif
+
index 8422e37..dcdac06 100644 (file)
@@ -30,7 +30,7 @@
 const char *getResult(OCStackResult result);
 std::string getIPAddrTBServer(OCClientResponse * clientResponse);
 std::string getPortTBServer(OCClientResponse * clientResponse);
-std::string getQueryStrForGetPut(unsigned  const char * responsePayload);
+std::string getQueryStrForGetPut(const char * responsePayload);
 
 #define TAG PCF("occlient")
 #define DEFAULT_CONTEXT_VALUE 0x99
@@ -57,7 +57,7 @@ unsigned static int TEST = TEST_INVALID;
 
 typedef struct
 {
-    unsigned char text[30];
+    char text[30];
     CLIENT_TEST test;
 } testToTextMap;
 
@@ -445,10 +445,11 @@ std::string getPortTBServer(OCClientResponse * clientResponse)
     return ss.str();
 }
 
-std::string getQueryStrForGetPut(unsigned  const char * responsePayload)
+std::string getQueryStrForGetPut(const char * responsePayload)
 {
 
-    std::string jsonPayload(reinterpret_cast<char*>(const_cast<unsigned char*>(responsePayload)));
+    std::string jsonPayload(responsePayload);
 
     return "/a/room";
 }
+
index dc230c4..a31b9c7 100644 (file)
@@ -57,7 +57,7 @@ void handleSigInt(int signum)
 
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
+    OC_LOG(INFO, TAG, "Usage : occlient -c <0|1> -u <0|1> -t <1|2|3>");
     OC_LOG(INFO, TAG, "-c <0|1> : Send unicast messages over Ethernet or WIFI");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
@@ -322,3 +322,4 @@ void parseClientResponse(OCClientResponse * clientResponse)
     coapServerPort = getPortTBServer(clientResponse);
     coapServerResource = getQueryStrForGetPut(clientResponse);
 }
+
index a2df222..8b6bcc4 100644 (file)
@@ -94,3 +94,4 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse);
 
 #endif
+
index 9e76255..dbfeec7 100644 (file)
@@ -470,7 +470,7 @@ OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag,
             response.requestHandle = entityHandlerRequest->requestHandle;
             response.resourceHandle = entityHandlerRequest->resource;
             response.ehResult = ehResult;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             // Indicate that response is NOT in a persistent buffer
             response.persistentBufferFlag = 0;
@@ -572,7 +572,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
             response.requestHandle = entityHandlerRequest->requestHandle;
             response.resourceHandle = entityHandlerRequest->resource;
             response.ehResult = ehResult;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             // Indicate that response is NOT in a persistent buffer
             response.persistentBufferFlag = 0;
@@ -683,7 +683,7 @@ void *ChangeLightRepresentation (void *param)
                 char * obsResp = cJSON_Print(json);
                 cJSON_Delete(json);
                 result = OCNotifyListOfObservers (Light.handle, obsNotify, j,
-                        (unsigned char *)obsResp, OC_NA_QOS);
+                        obsResp, OC_NA_QOS);
                 free(obsResp);
             }
             else if (gObserveNotifyType == 0)
@@ -1032,3 +1032,4 @@ OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufactu
     DeleteDeviceInfo();
     return OC_STACK_ERROR;
 }
+
index 3eb0943..d5167ca 100644 (file)
@@ -49,6 +49,13 @@ char *gResourceUri= (char *)"/a/led";
 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
 {
     cJSON *json = cJSON_CreateObject();
+
+    if(!json)
+    {
+        OC_LOG (ERROR, TAG, "json object not created properly");
+        return NULL;
+    }
+
     cJSON *format;
     char *jsonResponse;
     LEDResource *currLEDResource = &LED;
@@ -67,6 +74,13 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     if(OC_REST_PUT == ehRequest->method)
     {
         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+
+        if(!putJson)
+        {
+            OC_LOG (ERROR, TAG, "putJson object not created properly");
+            cJSON_Delete(json);
+            return NULL;
+        }
         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
                 "on") ? true:false);
         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
@@ -74,7 +88,16 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     }
 
     cJSON_AddStringToObject(json,"href",gResourceUri);
-    cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+    format = cJSON_CreateObject();
+
+    if(!format)
+    {
+        OC_LOG (ERROR, TAG, "format object not created properly");
+        cJSON_Delete(json);
+        return NULL;
+    }
+
+    cJSON_AddItemToObject(json, "rep", format);
     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
 
@@ -83,51 +106,68 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     return jsonResponse;
 }
 
-OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+        uint16_t maxPayloadSize)
 {
     OCEntityHandlerResult ehResult;
     char *getResp = constructJsonResponse(ehRequest);
 
-    if (maxPayloadSize > strlen ((char *)getResp))
+    if(getResp)
     {
-        strncpy(payload, getResp, strlen((char *)getResp));
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen ((char *)getResp))
+        {
+            strncpy(payload, getResp, strlen((char *)getResp));
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(getResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(getResp);
-
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+        uint16_t maxPayloadSize)
 {
     OCEntityHandlerResult ehResult;
     char *putResp = constructJsonResponse(ehRequest);
 
-    if (maxPayloadSize > strlen ((char *)putResp))
+    if(putResp)
     {
-        strncpy(payload, putResp, strlen((char *)putResp));
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen ((char *)putResp))
+        {
+            strncpy(payload, putResp, strlen((char *)putResp));
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(putResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(putResp);
-
     return ehResult;
 }
 
-OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize)
+OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload,
+        uint16_t maxPayloadSize)
 {
     char *respPLPost_led = NULL;
     cJSON *json;
@@ -154,9 +194,20 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, cha
             snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance);
 
             json = cJSON_CreateObject();
+            if(!json)
+            {
+                return OC_EH_ERROR;
+            }
 
             cJSON_AddStringToObject(json,"href",gResourceUri);
-            cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+            format = cJSON_CreateObject();
+
+            if(!format)
+            {
+                return OC_EH_ERROR;
+            }
+
+            cJSON_AddItemToObject(json, "rep", format);
             cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
@@ -258,7 +309,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 response.requestHandle = entityHandlerRequest->requestHandle;
                 response.resourceHandle = entityHandlerRequest->resource;
                 response.ehResult = ehResult;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
@@ -345,3 +396,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 71d8d46..5f65d4d 100644 (file)
@@ -216,7 +216,7 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
                 response.requestHandle = ehRequest->requestHandle;
                 response.resourceHandle = ehRequest->resource;
                 response.ehResult = ret;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions,
@@ -288,7 +288,7 @@ OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag,
                 response.requestHandle = ehRequest->requestHandle;
                 response.resourceHandle = ehRequest->resource;
                 response.ehResult = ret;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions,
@@ -353,7 +353,7 @@ OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag,
             response.requestHandle = ehRequest->requestHandle;
             response.resourceHandle = ehRequest->resource;
             response.ehResult = ret;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             response.numSendVendorSpecificHeaderOptions = 0;
             memset(response.sendVendorSpecificHeaderOptions,
@@ -413,7 +413,7 @@ OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag,
             response.requestHandle = ehRequest->requestHandle;
             response.resourceHandle = ehRequest->resource;
             response.ehResult = ret;
-            response.payload = (unsigned char *)payload;
+            response.payload = payload;
             response.payloadSize = strlen(payload);
             response.numSendVendorSpecificHeaderOptions = 0;
             memset(response.sendVendorSpecificHeaderOptions,
@@ -593,3 +593,4 @@ void createResources()
     res = OCBindResource(room, fan);
     OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res));
 }
+
index a403915..533787a 100644 (file)
@@ -50,6 +50,13 @@ char *gResourceUri= (char *)"/a/led";
 char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
 {
     cJSON *json = cJSON_CreateObject();
+
+    if(!json)
+    {
+        OC_LOG(ERROR, TAG, "CreateObject result in null for json");
+        return NULL;
+    }
+
     cJSON *format;
     char *jsonResponse;
     LEDResource *currLEDResource = &LED;
@@ -72,6 +79,14 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     if(OC_REST_PUT == ehRequest->method)
     {
         cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload);
+
+        if(!putJson)
+        {
+            OC_LOG(ERROR, TAG, "CreateObject result in null for putJson");
+            cJSON_Delete(json);
+            return NULL;
+        }
+
         currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring ,
                 "on") ? true:false);
         currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble;
@@ -79,7 +94,16 @@ char* constructJsonResponse (OCEntityHandlerRequest *ehRequest)
     }
 
     cJSON_AddStringToObject(json,"href",gResourceUri);
-    cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
+    format = cJSON_CreateObject();
+
+    if(!format)
+    {
+        OC_LOG(ERROR, TAG, "CreateObject result in null for format");
+        cJSON_Delete(json);
+        return NULL;
+    }
+
+    cJSON_AddItemToObject(json, "rep", format);
     cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off"));
     cJSON_AddNumberToObject(format, "power", currLEDResource->power);
 
@@ -103,7 +127,7 @@ void ProcessGetRequest (OCEntityHandlerRequest *ehRequest)
     response.requestHandle = ehRequest->requestHandle;
     response.resourceHandle = ehRequest->resource;
     response.ehResult = OC_EH_OK;
-    response.payload = (unsigned char *)getResp;
+    response.payload = getResp;
     response.payloadSize = strlen(getResp) + 1;
     response.numSendVendorSpecificHeaderOptions = 0;
     memset(response.sendVendorSpecificHeaderOptions,
@@ -132,13 +156,13 @@ OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest
         memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
         // Do deep copy of query
         request->query =
-                (unsigned char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
+                (char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1);
         if (request->query)
         {
             strcpy((char *)request->query, (const char *)entityHandlerRequest->query);
 
             // Copy the request payload
-            request->reqJSONPayload = (unsigned char * )OCMalloc(
+            request->reqJSONPayload = (char * )OCMalloc(
                             strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1);
             if (request->reqJSONPayload)
             {
@@ -347,3 +371,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 451d3f5..c312d35 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 Import('env')
 
@@ -54,3 +73,4 @@ gen_sec_bin = samples_env.Program('gen_sec_bin', ['gen_sec_bin.cpp'])
 Alias("samples", [ocserverbasicops, occlientbasicops])
 
 env.AppendTarget('samples')
+
index 0a65ea0..e5aad51 100644 (file)
@@ -166,12 +166,12 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             {
                 case TEST_NON_CON_OP:
                     InitGetRequest(OC_LOW_QOS);
-                    InitPutRequest();
+                    InitPutRequest(OC_LOW_QOS);
                     //InitPostRequest(OC_LOW_QOS);
                     break;
                 case TEST_CON_OP:
                     InitGetRequest(OC_HIGH_QOS);
-                    InitPutRequest();
+                    InitPutRequest(OC_HIGH_QOS);
                     //InitPostRequest(OC_HIGH_QOS);
                     break;
             }
@@ -182,13 +182,14 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
 }
 
-int InitPutRequest()
+int InitPutRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
         << ":" << coapServerPort  << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
+    return (InvokeOCDoResource(query, OC_REST_PUT,
+            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
@@ -235,7 +236,7 @@ int InitGetRequest(OCQualityOfService qos)
             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
 }
 
-int InitDiscovery()
+int InitDiscovery(OCQualityOfService qos)
 {
     OCStackResult ret;
     OCCallbackData cbData;
@@ -278,7 +279,8 @@ int InitDiscovery()
         szQueryUri);
 
     ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
-            discoveryReqConnType, OC_LOW_QOS, &cbData, NULL, 0);
+            discoveryReqConnType, ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS),
+            &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -331,7 +333,14 @@ int main(int argc, char* argv[])
         return 0;
     }
 
-    InitDiscovery();
+    if(TEST_CASE == TEST_NON_CON_OP)
+    {
+        InitDiscovery(OC_LOW_QOS);
+    }
+    else if(TEST_CASE == TEST_CON_OP)
+    {
+        InitDiscovery(OC_HIGH_QOS);
+    }
 
     timeout.tv_sec  = 0;
     timeout.tv_nsec = 100000000L;
@@ -458,3 +467,4 @@ int parseClientResponse(OCClientResponse * clientResponse)
     }
     return 0;
 }
+
index 689d7e6..8f8326c 100644 (file)
@@ -53,10 +53,10 @@ std::string getQueryStrForGetPut(OCClientResponse * clientResponse);
 /* Following are initialization functions for GET, PUT
  * POST & Discovery operations
  */
-int InitPutRequest();
+int InitPutRequest(OCQualityOfService qos);
 int InitGetRequest(OCQualityOfService qos);
 int InitPostRequest(OCQualityOfService qos);
-int InitDiscovery();
+int InitDiscovery(OCQualityOfService qos);
 
 /* Function to retrieve ip address, port no. of the server
  *  and query for the operations to be performed.
index 4105740..582902c 100644 (file)
@@ -91,20 +91,27 @@ OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
     OCEntityHandlerResult ehResult;
 
     char *getResp = constructJsonResponse(ehRequest);
-    if (maxPayloadSize > strlen (getResp))
+    if(getResp)
     {
-        strcpy(payload, getResp);
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen (getResp))
+        {
+            strcpy(payload, getResp);
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(getResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(getResp);
-
     return ehResult;
 }
 
@@ -114,20 +121,28 @@ OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest,
     OCEntityHandlerResult ehResult;
 
     char *putResp = constructJsonResponse(ehRequest);
-    if (maxPayloadSize > strlen (putResp))
+
+    if(putResp)
     {
-        strcpy(payload, putResp);
-        ehResult = OC_EH_OK;
+        if (maxPayloadSize > strlen (putResp))
+        {
+            strcpy(payload, putResp);
+            ehResult = OC_EH_OK;
+        }
+        else
+        {
+            OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
+                    maxPayloadSize);
+            ehResult = OC_EH_ERROR;
+        }
+
+        free(putResp);
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
-                maxPayloadSize);
         ehResult = OC_EH_ERROR;
     }
 
-    free(putResp);
-
     return ehResult;
 }
 
@@ -265,7 +280,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 response.requestHandle = entityHandlerRequest->requestHandle;
                 response.resourceHandle = entityHandlerRequest->resource;
                 response.ehResult = ehResult;
-                response.payload = (unsigned char *)payload;
+                response.payload = payload;
                 response.payloadSize = strlen(payload);
                 response.numSendVendorSpecificHeaderOptions = 0;
                 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
@@ -366,3 +381,4 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 
     return 0;
 }
+
index 48a46a1..d93c69d 100644 (file)
 #define TAG PCF("occlientcb")
 
 struct ClientCB *cbList = NULL;
-OCMulticastNode * mcPresenceNodes = NULL;
+static OCMulticastNode * mcPresenceNodes = NULL;
 
 OCStackResult
 AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
              CAToken_t * token, OCDoHandle *handle, OCMethod method,
-             unsigned char * requestUri, unsigned char * resourceTypeName)
+             char * requestUri, char * resourceTypeName)
 {
+    if(!clientCB || !cbData || !token || !handle || !requestUri)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     ClientCB *cbNode = NULL;
 
@@ -100,7 +104,8 @@ AddClientCB (ClientCB** clientCB, OCCallbackData* cbData,
         return OC_STACK_NO_MEMORY;
 }
 
-void DeleteClientCB(ClientCB * cbNode) {
+void DeleteClientCB(ClientCB * cbNode)
+{
     if(cbNode) {
         LL_DELETE(cbList, cbNode);
         OC_LOG(INFO, TAG, PCF("deleting tokens"));
@@ -136,7 +141,7 @@ void DeleteClientCB(ClientCB * cbNode) {
     }
 }
 
-ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned char * requestUri)
+ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const char * requestUri)
 {
     ClientCB* out = NULL;
     if(token) {
@@ -159,7 +164,8 @@ ClientCB* GetClientCB(const CAToken_t * token, OCDoHandle handle, const unsigned
     }
     else if(requestUri) {
         LL_FOREACH(cbList, out) {
-            if(out->requestUri && strcmp((char *)out->requestUri, (char *)requestUri) == 0) {
+            if(out->requestUri && strcmp(out->requestUri, requestUri ) == 0)
+            {
                 return out;
             }
         }
@@ -215,8 +221,13 @@ void FindAndDeleteClientCB(ClientCB * cbNode) {
     }
 }
 
-OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce)
+OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, char* uri, uint32_t nonce)
 {
+    if(!outnode)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCMulticastNode *node;
 
     node = (OCMulticastNode*) OCMalloc(sizeof(OCMulticastNode));
@@ -232,12 +243,12 @@ OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, u
     return OC_STACK_NO_MEMORY;
 }
 
-OCMulticastNode* GetMCPresenceNode(const unsigned char * uri) {
+OCMulticastNode* GetMCPresenceNode(const char * uri) {
     OCMulticastNode* out = NULL;
 
     if(uri) {
         LL_FOREACH(mcPresenceNodes, out) {
-            if(out->uri && strcmp((char *)out->uri, (char *)uri) == 0) {
+            if(out->uri && strcmp(out->uri, uri) == 0) {
                 return out;
             }
         }
@@ -245,3 +256,4 @@ OCMulticastNode* GetMCPresenceNode(const unsigned char * uri) {
     OC_LOG(INFO, TAG, PCF("MulticastNode Not found !!"));
     return NULL;
 }
+
index 246b263..5a8aa8a 100644 (file)
 
 static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr)
 {
+    if(!resource || !rtPtr)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCResourceType* rTPointer = resource->rsrcType;
     while (rTPointer)
     {
         if( strcmp (rTPointer->resourcetypename, rtPtr) == 0)
+        {
             return OC_STACK_OK;
+        }
 
         rTPointer = rTPointer->next;
     }
@@ -51,11 +58,18 @@ static OCStackResult CheckRTParamSupport(const OCResource* resource, const char*
 
 static OCStackResult CheckIFParamSupport(const OCResource* resource, const char* ifPtr)
 {
+    if(!resource || !ifPtr)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCResourceInterface* iFPointer = resource->rsrcInterface;
     while (iFPointer)
     {
         if( strcmp (iFPointer->name, ifPtr) == 0)
-             return OC_STACK_OK;
+        {
+            return OC_STACK_OK;
+        }
 
         iFPointer = iFPointer->next;
     }
@@ -63,10 +77,11 @@ static OCStackResult CheckIFParamSupport(const OCResource* resource, const char*
 }
 
 static OCStackResult
-ValidateQuery (const unsigned char *query, OCResourceHandle resource,
+ValidateQuery (const char *query, OCResourceHandle resource,
                              OCStackIfTypes *ifParam, char **rtParam)
 {
-    uint8_t numFields = 0, numParam;
+    uint8_t numFields = 0;
+    uint8_t numParam;
 
     //TODO: Query and URL validation is being done for virtual resource case
     // using ValidateUrlQuery function. We should be able to merge it with this
@@ -76,6 +91,11 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
     if (!query)
         return OC_STACK_ERROR;
 
+    if(!ifParam || !rtParam)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     if (!(*query))
     {
         // Query string is empty
@@ -102,16 +122,20 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
         while (innerToken != NULL)
         {
             numParam++;
-            if (strcmp (innerToken, OC_RSRVD_INTERFACE) == 0)
+            if (strncmp (innerToken, OC_RSRVD_INTERFACE, sizeof(OC_RSRVD_INTERFACE)) == 0)
             {
                 // Determine the value of IF parameter
                 innerToken = strtok_r (NULL, "=", &endToken);
                 ifPtr = innerToken;
-            } else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0) {
+            }
+            else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0)
+            {
                 // Determine the value of RT parameter
                 innerToken = strtok_r (NULL, "=", &endToken);
                 rtPtr = innerToken;
-            } else {
+            }
+            else
+            {
                 innerToken = strtok_r (NULL, "=", &endToken);
             }
         }
@@ -124,7 +148,7 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
     }
     if (numFields > NUM_PARAM_IN_QUERY)
     {
-        // M1 release supports one IF value, one RT value and no other params
+        // current release supports one IF value, one RT value and no other params
         return OC_STACK_INVALID_QUERY;
     }
 
@@ -184,7 +208,7 @@ ValidateQuery (const unsigned char *query, OCResourceHandle resource,
 
 
 static OCStackResult BuildRootResourceJSON(OCResource *resource,
-        unsigned char * bufferPtr, uint16_t *remaining)
+        char * bufferPtr, uint16_t *remaining)
 {
     OCStackResult ret = OC_STACK_ERROR;
     cJSON *resObj;
@@ -202,14 +226,14 @@ static OCStackResult BuildRootResourceJSON(OCResource *resource,
     jsonLen = strlen(jsonStr);
     if (jsonLen < *remaining)
     {
-        strcpy((char*) bufferPtr, jsonStr);
+        strncpy(bufferPtr, jsonStr, jsonLen);
         *remaining -= jsonLen;
         bufferPtr += jsonLen;
         ret = OC_STACK_OK;
     }
 
     cJSON_Delete (resObj);
-    free (jsonStr);
+    OCFree(jsonStr);
 
     return ret;
 }
@@ -219,11 +243,16 @@ static OCStackResult
 HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
                        uint8_t filterOn, char *filterValue)
 {
+    if(!ehRequest)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult ret = OC_STACK_ERROR;
-    unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
+    char jsonbuffer[MAX_RESPONSE_LENGTH] = {};
     size_t jsonbufferLength = 0;
     uint16_t remaining = 0;
-    unsigned char * ptr = NULL;
+    char * ptr = NULL;
     OCResource * collResource = (OCResource *) ehRequest->resource;
 
     ptr = jsonbuffer;
@@ -278,7 +307,7 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest,
     jsonbufferLength = strlen((const char *)jsonbuffer);
     if(ret == OC_STACK_OK && jsonbufferLength)
     {
-        OCEntityHandlerResponse response = {0};
+        OCEntityHandlerResponse response = {};
         response.ehResult = OC_EH_OK;
         response.payload = jsonbuffer;
         response.payloadSize = jsonbufferLength + 1;
@@ -295,10 +324,10 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
 {
     OCStackResult stackRet = OC_STACK_ERROR;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
+    char jsonbuffer[MAX_RESPONSE_LENGTH] = {0};
     size_t jsonbufferLength = 0;
     uint16_t remaining = 0;
-    unsigned char * ptr = NULL;
+    char * ptr = NULL;
     OCResource * collResource = (OCResource *) ehRequest->resource;
 
     ptr = jsonbuffer;
@@ -311,7 +340,7 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
     jsonbufferLength = strlen((const char *)jsonbuffer);
     if(jsonbufferLength)
     {
-        OCEntityHandlerResponse response = {0};
+        OCEntityHandlerResponse response = {};
         response.ehResult = OC_EH_OK;
         response.payload = jsonbuffer;
         response.payloadSize = jsonbufferLength + 1;
@@ -361,21 +390,33 @@ HandleBatchInterface(OCEntityHandlerRequest *ehRequest)
 
 uint8_t GetNumOfResourcesInCollection (OCResource *resource)
 {
-    uint8_t num = 0;
-    for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    if(resource)
     {
-        if (resource->rsrcResources[i])
+        uint8_t num = 0;
+        for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
         {
-            num++;
+            if (resource->rsrcResources[i])
+            {
+                num++;
+            }
         }
+        return num;
+    }
+    else
+    {
+        return -1;
     }
-    return num;
 }
 
 
 OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                                               OCEntityHandlerRequest *ehRequest)
 {
+    if(!ehRequest || !ehRequest->query)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     OCStackIfTypes ifQueryParam = STACK_IF_INVALID;
     char *rtQueryParam = NULL;
@@ -383,19 +424,24 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
     OC_LOG_V(INFO, TAG, "DefaultCollectionEntityHandler with query %s", ehRequest->query);
 
     if (flag != OC_REQUEST_FLAG)
+    {
         return OC_STACK_ERROR;
+    }
 
-    result = ValidateQuery ((const unsigned char *)ehRequest->query,
+    result = ValidateQuery (ehRequest->query,
                             ehRequest->resource, &ifQueryParam, &rtQueryParam);
 
     if (result != OC_STACK_OK)
+    {
         return result;
+    }
 
-  
-    if(!((ehRequest->method == OC_REST_GET) || 
+    if(!((ehRequest->method == OC_REST_GET) ||
         (ehRequest->method == OC_REST_PUT) ||
         (ehRequest->method == OC_REST_POST)))
+    {
         return OC_STACK_ERROR;
+    }
 
     if (ehRequest->method == OC_REST_GET)
     {
@@ -414,7 +460,8 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
 
             case STACK_IF_BATCH:
                 OC_LOG(INFO, TAG, PCF("STACK_IF_BATCH"));
-                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse;
+                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
+                                                                        HandleAggregateResponse;
                 ((OCServerRequest *)ehRequest->requestHandle)->numResponses =
                         GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
                 return HandleBatchInterface(ehRequest);
@@ -424,7 +471,9 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
             default:
                 return OC_STACK_ERROR;
         }
-    } else if (ehRequest->method == OC_REST_PUT) {
+    }
+    else if (ehRequest->method == OC_REST_PUT)
+    {
         switch (ifQueryParam)
         {
             case STACK_IF_DEFAULT:
@@ -436,7 +485,8 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
                 return OC_STACK_ERROR;
 
             case STACK_IF_BATCH:
-                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse;
+                ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler =
+                                                                        HandleAggregateResponse;
                 ((OCServerRequest *)ehRequest->requestHandle)->numResponses =
                         GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1;
                 return HandleBatchInterface(ehRequest);
@@ -455,19 +505,19 @@ OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag,
     else if (ehRequest->method == OC_REST_POST)
     {
 
-        switch (ifQueryParam)
+        if(ifQueryParam == STACK_IF_GROUP)
         {
-            case STACK_IF_GROUP:
-            {
-                OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
-                        ehRequest->reqJSONPayload);
-                return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
-                        (OCResource *) ehRequest->resource, ehRequest);
-            }
-            default:
-                return OC_STACK_ERROR;
+            OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ",
+                    ehRequest->reqJSONPayload);
+            return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/,
+                    (OCResource *) ehRequest->resource, ehRequest);
+        }
+        else
+        {
+            return OC_STACK_ERROR;
         }
     }
     return result;
 }
 
+
index 0d5e9ea..ef5e42e 100644 (file)
@@ -47,6 +47,12 @@ static struct ResourceObserver * serverObsList = NULL;
 OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver,
         OCQualityOfService appQoS)
 {
+    if(!resourceObserver)
+    {
+        OC_LOG(ERROR, TAG, "DetermineObserverQoS called with invalid resourceObserver");
+        return -1;
+    }
+
     OCQualityOfService decidedQoS = appQoS;
     if(appQoS == OC_NA_QOS)
     {
@@ -65,13 +71,13 @@ OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * reso
         if(resourceObserver->forceHighQos \
                 || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT)
         #endif
-            {
+        {
             resourceObserver->lowQosCount = 0;
             // at some point we have to to send CON to check on the
             // availability of observer
             OC_LOG(INFO, TAG, PCF("This time we are sending the  notification as High qos"));
             decidedQoS = OC_HIGH_QOS;
-            }
+        }
         else
         {
             (resourceObserver->lowQosCount)++;
@@ -89,11 +95,16 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 #endif
 {
     OC_LOG(INFO, TAG, PCF("Entering SendObserverNotification"));
+    if(!resPtr)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     ResourceObserver * resourceObserver = serverObsList;
     uint8_t numObs = 0;
     OCServerRequest * request = NULL;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
 
     // Find clients that are observing this resource
@@ -121,8 +132,10 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
                     {
                         result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
                                     request->method, (OCResourceHandle) resPtr, request->query,
-                                    request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
-                                    request->rcvdVendorSpecificHeaderOptions, OC_OBSERVE_NO_OPTION, 0);
+                                    request->reqJSONPayload,
+                                    request->numRcvdVendorSpecificHeaderOptions,
+                                    request->rcvdVendorSpecificHeaderOptions,
+                                    OC_OBSERVE_NO_OPTION, 0);
                         if(result == OC_STACK_OK)
                         {
                             ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest);
@@ -137,8 +150,8 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
             }
             else
             {
-                OCEntityHandlerResponse ehResponse = {0};
-                unsigned char presenceResBuf[MAX_RESPONSE_LENGTH] = {0};
+                OCEntityHandlerResponse ehResponse = {};
+                char presenceResBuf[MAX_RESPONSE_LENGTH] = {};
                 //This is effectively the implementation for the presence entity handler.
                 OC_LOG(DEBUG, TAG, PCF("This notification is for Presence"));
                 result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET,
@@ -184,15 +197,19 @@ OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr,
 
 OCStackResult SendListObserverNotification (OCResource * resource,
         OCObservationId  *obsIdList, uint8_t numberOfIds,
-        unsigned char *notificationJSONPayload, uint32_t maxAge,
+        const char *notificationJSONPayload, uint32_t maxAge,
         OCQualityOfService qos)
 {
+    if(!resource || !obsIdList || !notificationJSONPayload)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     uint8_t numIds = numberOfIds;
     ResourceObserver *observation = NULL;
     uint8_t numSentNotification = 0;
     OCServerRequest * request = NULL;
     OCStackResult result = OC_STACK_ERROR;
-    OCEntityHandlerResponse ehResponse = {0};
 
     OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification"));
     while(numIds)
@@ -218,16 +235,16 @@ OCStackResult SendListObserverNotification (OCResource * resource,
                     request->observeResult = OC_STACK_OK;
                     if(result == OC_STACK_OK)
                     {
-                        memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse));
+                        OCEntityHandlerResponse ehResponse = {};
                         ehResponse.ehResult = OC_EH_OK;
-                        ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
+                        ehResponse.payload = (char *) OCMalloc(MAX_RESPONSE_LENGTH);
                         if(!ehResponse.payload)
                         {
                             FindAndDeleteServerRequest(request);
                             continue;
                         }
-                        strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload);
-                        ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1;
+                        strncpy(ehResponse.payload, notificationJSONPayload, MAX_RESPONSE_LENGTH-1);
+                        ehResponse.payloadSize = strlen(ehResponse.payload) + 1;
                         ehResponse.persistentBufferFlag = 0;
                         ehResponse.requestHandle = (OCRequestHandle) request;
                         ehResponse.resourceHandle = (OCResourceHandle) resource;
@@ -293,32 +310,37 @@ OCStackResult AddObserver (const char         *resUri,
                            CAToken_t          *token,
                            OCResource         *resHandle,
                            OCQualityOfService qos,
-                           CAAddress_t          *addressInfo,
+                           const CAAddress_t  *addressInfo,
                            CAConnectivityType_t connectivityType)
 {
     ResourceObserver *obsNode = NULL;
 
+    if(!resUri || !token || !*token)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver));
     if (obsNode)
     {
         obsNode->observeId = obsId;
 
-        obsNode->resUri = (unsigned char *)OCMalloc(strlen(resUri)+1);
+        obsNode->resUri = (char *)OCMalloc(strlen(resUri)+1);
         VERIFY_NON_NULL (obsNode->resUri);
         memcpy (obsNode->resUri, resUri, strlen(resUri)+1);
 
         obsNode->qos = qos;
         if(query)
         {
-            obsNode->query = (unsigned char *)OCMalloc(strlen(query)+1);
+            obsNode->query = (char *)OCMalloc(strlen(query)+1);
             VERIFY_NON_NULL (obsNode->query);
             memcpy (obsNode->query, query, strlen(query)+1);
         }
 
         obsNode->token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
         VERIFY_NON_NULL (obsNode->token);
-        memset(obsNode->token, 0, CA_MAX_TOKEN_LEN + 1);
         memcpy(obsNode->token, *token, CA_MAX_TOKEN_LEN);
+        obsNode->token[CA_MAX_TOKEN_LEN]='\0';
 
         obsNode->addressInfo = *addressInfo;
         obsNode->connectivityType = connectivityType;
@@ -359,7 +381,7 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t * token)
 {
     ResourceObserver *out = NULL;
 
-    if(token)
+    if(token && *token)
     {
         LL_FOREACH (serverObsList, out)
         {
@@ -378,6 +400,11 @@ ResourceObserver* GetObserverUsingToken (const CAToken_t * token)
 
 OCStackResult DeleteObserverUsingToken (CAToken_t * token)
 {
+    if(!token || !*token)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     ResourceObserver *obsNode = NULL;
 
     obsNode = GetObserverUsingToken (token);
@@ -400,7 +427,10 @@ void DeleteObserverList()
     ResourceObserver *tmp = NULL;
     LL_FOREACH_SAFE (serverObsList, out, tmp)
     {
-        DeleteObserverUsingToken (&(out->token));
+        if(out)
+        {
+            DeleteObserverUsingToken (&(out->token));
+        }
     }
     serverObsList = NULL;
 }
@@ -411,6 +441,11 @@ CreateObserveHeaderOption (CAHeaderOption_t **caHdrOpt,
                            uint8_t numOptions,
                            uint8_t observeFlag)
 {
+    if(!caHdrOpt)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     CAHeaderOption_t *tmpHdrOpt = NULL;
 
     tmpHdrOpt = (CAHeaderOption_t *) OCMalloc ((numOptions+1)*sizeof(CAHeaderOption_t));
@@ -436,16 +471,24 @@ GetObserveHeaderOption (uint32_t * observationOption,
                         CAHeaderOption_t *options,
                         uint8_t * numOptions)
 {
+    if(!observationOption)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
     *observationOption = OC_OBSERVE_NO_OPTION;
-    uint8_t i = 0;
-    uint8_t c = 0;
-    for(i = 0; i < *numOptions; i++)
+
+    if(!options || !numOptions)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    for(uint8_t i = 0; i < *numOptions; i++)
     {
         if(options[i].protocolID == CA_COAP_ID &&
                 options[i].optionID == COAP_OPTION_OBSERVE)
         {
             *observationOption = options[i].optionData[0];
-            for(c = i; c < *numOptions-1; c++)
+            for(uint8_t c = i; c < *numOptions-1; c++)
             {
                 options[i].protocolID = options[i+1].protocolID;
                 options[i].optionID = options[i+1].optionID;
@@ -458,3 +501,4 @@ GetObserveHeaderOption (uint32_t * observationOption,
     }
     return OC_STACK_OK;
 }
+
index 1832397..bc440c8 100644 (file)
@@ -26,6 +26,7 @@
 #include "ocresourcehandler.h"
 #include "ocobserve.h"
 #include "occollection.h"
+#include "ocmalloc.h"
 #include "logger.h"
 #include "cJSON.h"
 
@@ -65,8 +66,8 @@ OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag,
     return  OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures
 }
 
-/* This method  will return the port at which the secure resource is hosted */
-static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *port)
+/* This method will retrieve the port at which the secure resource is hosted */
+static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint16_t *port)
 {
     CALocalConnectivity_t* info = NULL;
     uint32_t size = 0;
@@ -77,7 +78,7 @@ static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *
     {
         while (size--)
         {
-            if (info[size].isSecured == true && info[size].type == connType)
+            if (info[size].isSecured && info[size].type == connType)
             {
                 if (info[size].type == CA_ETHERNET ||
                     info[size].type == CA_WIFI)
@@ -90,54 +91,76 @@ static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint32_t *
         }
     }
 
-    free(info);
+    OCFree(info);
     return ret;
 }
 
-static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query,
+static OCStackResult ValidateUrlQuery (char *url, char *query,
                                 uint8_t *filterOn, char **filterValue)
 {
-    char *filterParam;
+    if(!filterOn || !filterValue)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    char *filterParam = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering ValidateUrlQuery"));
     if (!url)
+    {
         return OC_STACK_INVALID_URI;
+    }
 
     if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0 ||
-                strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0) {
+                strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0)
+    {
         *filterOn = STACK_RES_DISCOVERY_NOFILTER;
-        if (query && *query) {
-            char* strTokPtr;
+        if (query && *query)
+        {
+            char* strTokPtr = NULL;
             filterParam = strtok_r((char *)query, "=", &strTokPtr);
             *filterValue = strtok_r(NULL, " ", &strTokPtr);
-            if (!(*filterValue)) {
+            if (!(*filterValue))
+            {
                 return OC_STACK_INVALID_QUERY;
-            } else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0)
+            {
                 // Resource discovery with interface filter
                 *filterOn = STACK_RES_DISCOVERY_IF_FILTER;
-            } else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0)
+            {
                 // Resource discovery with resource type filter
                 *filterOn = STACK_RES_DISCOVERY_RT_FILTER;
-            } else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0)
+            {
                 //Device ID filter
                 *filterOn = STACK_DEVICE_DISCOVERY_DI_FILTER;
-            } else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0) {
+            }
+            else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0)
+            {
                 //Device Name filter
                 *filterOn = STACK_DEVICE_DISCOVERY_DN_FILTER;
-            } else {
+            }
+            else
+            {
                 // Other filter types not supported
                 return OC_STACK_INVALID_QUERY;
             }
         }
     }
     #ifdef WITH_PRESENCE
-    else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0) {
+    else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0)
+    {
         //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK.
         OC_LOG(INFO, TAG, PCF("OC_PRESENCE Request"));
         *filterOn = STACK_RES_DISCOVERY_NOFILTER;
     }
     #endif
-    else {
+    else
+    {
         // Other URIs not yet supported
         return OC_STACK_INVALID_URI;
     }
@@ -151,13 +174,20 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
                         char *filterValue, char * out, uint16_t *remaining,
                         CAConnectivityType_t connType )
 {
-    OCResourceType *resourceTypePtr;
-    OCResourceInterface *interfacePtr;
-    cJSON *resObj, *propObj, *rtArray;
-    char *jsonStr;
+    if(!resourcePtr || !out  || !remaining)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    OCResourceType *resourceTypePtr = NULL;
+    OCResourceInterface *interfacePtr = NULL;
+    cJSON *resObj = NULL;
+    cJSON *propObj = NULL;
+    cJSON *rtArray = NULL;
+    char *jsonStr = NULL;
     uint8_t encodeRes = 0;
     OCStackResult ret = OC_STACK_OK;
-    uint16_t jsonLen;
+    uint16_t jsonLen = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponse"));
     resObj = cJSON_CreateObject();
@@ -165,47 +195,58 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
     if (resourcePtr)
     {
         encodeRes = 0;
-        if (filterOn == STACK_RES_DISCOVERY_RT_FILTER) {
+        if (filterOn == STACK_RES_DISCOVERY_RT_FILTER)
+        {
             resourceTypePtr = resourcePtr->rsrcType;
-            while (resourceTypePtr) {
-                if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0) {
+            while (resourceTypePtr)
+            {
+                if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0)
+                {
                     encodeRes = 1;
                     break;
                 }
                 resourceTypePtr = resourceTypePtr->next;
             }
-        } else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER) {
+        }
+        else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER)
+        {
             interfacePtr = resourcePtr->rsrcInterface;
-            while (interfacePtr) {
-                if (strcmp (interfacePtr->name, filterValue) == 0) {
+            while (interfacePtr)
+            {
+                if (strcmp (interfacePtr->name, filterValue) == 0)
+                {
                     encodeRes = 1;
                     break;
                 }
                 interfacePtr = interfacePtr->next;
             }
-        } else if (filterOn == STACK_RES_DISCOVERY_NOFILTER) {
+        }
+        else if (filterOn == STACK_RES_DISCOVERY_NOFILTER)
+        {
             encodeRes = 1;
-        } else {
+        }
+        else
+        {
             //TODO: Unsupported query filter
             return OC_STACK_INVALID_QUERY;
         }
 
-        if (encodeRes) {
+        if (encodeRes)
+        {
             // Add URIs
             cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri));
 
             // Add server instance id
-            const char* serverInstanceId = OCGetServerInstanceIDString();
             cJSON_AddItemToObject (resObj,
                                    OC_RSRVD_SERVER_INSTANCE_ID,
-                                   cJSON_CreateString(serverInstanceId));
-            serverInstanceId = NULL;
+                                   cJSON_CreateString(OCGetServerInstanceIDString()));
 
             cJSON_AddItemToObject (resObj, "prop", propObj = cJSON_CreateObject());
             // Add resource types
             cJSON_AddItemToObject (propObj, OC_RSRVD_RESOURCE_TYPE, rtArray = cJSON_CreateArray());
             resourceTypePtr = resourcePtr->rsrcType;
-            while (resourceTypePtr) {
+            while (resourceTypePtr)
+            {
                 cJSON_AddItemToArray (rtArray,
                                       cJSON_CreateString(resourceTypePtr->resourcetypename));
                 resourceTypePtr = resourceTypePtr->next;
@@ -213,22 +254,26 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
             // Add interface types
             cJSON_AddItemToObject (propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray());
             interfacePtr = resourcePtr->rsrcInterface;
-            while (interfacePtr) {
+            while (interfacePtr)
+            {
                 cJSON_AddItemToArray (rtArray, cJSON_CreateString(interfacePtr->name));
                 interfacePtr = interfacePtr->next;
             }
             // If resource is observable, set observability flag.
             // Resources that are not observable will not have the flag.
-            if (resourcePtr->resourceProperties & OC_OBSERVABLE) {
+            if (resourcePtr->resourceProperties & OC_OBSERVABLE)
+            {
                 cJSON_AddItemToObject (propObj, OC_RSRVD_OBSERVABLE,
                                        cJSON_CreateNumber(OC_RESOURCE_OBSERVABLE));
             }
             // Set secure flag for secure resources
-            if (resourcePtr->resourceProperties & OC_SECURE) {
+            if (resourcePtr->resourceProperties & OC_SECURE)
+            {
                 cJSON_AddNumberToObject (propObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE);
                 //Set the IP port also as secure resources are hosted on a different port
-                uint32_t port;
-                if (GetSecurePortInfo (connType, &port) == OC_STACK_OK) {
+                uint16_t port = 0;
+                if (GetSecurePortInfo (connType, &port) == OC_STACK_OK)
+                {
                     cJSON_AddNumberToObject (propObj, OC_RSRVD_HOSTING_PORT, port);
                 }
             }
@@ -248,7 +293,7 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
         ret = OC_STACK_ERROR;
     }
     cJSON_Delete (resObj);
-    free (jsonStr);
+    OCFree (jsonStr);
 
     OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponse"));
     return ret;
@@ -257,6 +302,11 @@ BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn,
 OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filterValue,
                                                     char *out, uint16_t *remaining)
 {
+    if(!out || !remaining)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult ret = OC_STACK_ERROR;
 
     if (savedDeviceInfo != NULL)
@@ -269,16 +319,18 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
 
         if (filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER)
         {
-            if((cJSON_GetObjectItem(repObj,"di") != NULL) &&
-                    strcmp(cJSON_GetObjectItem(repObj,"di")->valuestring, filterValue) == 0)
+            if((cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_ID) != NULL) &&
+                    strcmp(cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_ID)->valuestring, filterValue)
+                    == 0)
             {
                 ret = OC_STACK_OK;
             }
         }
         else if (filterOn == STACK_DEVICE_DISCOVERY_DN_FILTER)
         {
-            if((cJSON_GetObjectItem(repObj,"dn") != NULL) &&
-                    strcmp(cJSON_GetObjectItem(repObj,"dn")->valuestring, filterValue) == 0)
+            if((cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_NAME) != NULL) &&
+                    strcmp(cJSON_GetObjectItem(repObj,OC_RSRVD_DEVICE_NAME)->valuestring,
+                        filterValue) == 0)
             {
                 ret = OC_STACK_OK;
             }
@@ -311,7 +363,7 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
                     ret = OC_STACK_ERROR;
                 }
 
-                free(jsonStr);
+                OCFree(jsonStr);
             }
             else
             {
@@ -333,7 +385,6 @@ OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filt
     return ret;
 }
 
-//TODO ("Does it make sense to make this method as inline")
 const char * GetVirtualResourceUri( OCVirtualResources resource)
 {
     if (resource < OC_MAX_VIRTUAL_RESOURCES)
@@ -346,6 +397,11 @@ const char * GetVirtualResourceUri( OCVirtualResources resource)
 
 uint8_t IsVirtualResource(const char* resourceUri)
 {
+    if(!resourceUri)
+    {
+        return 0;
+    }
+
     for (int i = 0; i < OC_MAX_VIRTUAL_RESOURCES; i++)
     {
         if (strcmp(resourceUri, GetVirtualResourceUri((OCVirtualResources)i)) == 0)
@@ -358,6 +414,11 @@ uint8_t IsVirtualResource(const char* resourceUri)
 
 uint8_t IsCollectionResource (OCResource *resource)
 {
+    if(!resource)
+    {
+        return 0;
+    }
+
     for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++)
     {
         if (resource->rsrcResources[i])
@@ -370,6 +431,11 @@ uint8_t IsCollectionResource (OCResource *resource)
 
 OCResource *FindResourceByUri(const char* resourceUri)
 {
+    if(!resourceUri)
+    {
+        return NULL;
+    }
+
     OCResource * pointer = headResource;
     while (pointer) {
         if (strcmp(resourceUri, pointer->uri) == 0) {
@@ -386,6 +452,10 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
                                          ResourceHandling *handling,
                                          OCResource **resource)
 {
+    if(!request || !handling || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OC_LOG(INFO, TAG, PCF("Entering DetermineResourceHandling"));
 
@@ -400,7 +470,7 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
     {
         // Resource URL not specified
         *handling = OC_RESOURCE_NOT_SPECIFIED;
-        return OC_STACK_OK;
+        return OC_STACK_NO_RESOURCE;
     }
     else
     {
@@ -424,7 +494,7 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
         // secure resource will entertain only authorized requests
         if ((resourcePtr->resourceProperties & OC_SECURE) && (request->secured == 0))
         {
-            OC_LOG(INFO, TAG, PCF("Un-authorized request. Ignore it!"));
+            OC_LOG(ERROR, TAG, PCF("Un-authorized request. Ignoring"));
             return OC_STACK_RESOURCE_ERROR;
         }
 
@@ -435,17 +505,23 @@ OCStackResult DetermineResourceHandling (OCServerRequest *request,
             {
                 *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER;
                 return OC_STACK_OK;
-            } else {
+            }
+            else
+            {
                 *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER;
                 return OC_STACK_OK;
             }
-        } else {
+        }
+        else
+        {
             // Resource not a collection
             if (resourcePtr->entityHandler != defaultResourceEHandler)
             {
                 *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER;
                 return OC_STACK_OK;
-            } else {
+            }
+            else
+            {
                 *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER;
                 return OC_STACK_OK;
             }
@@ -487,13 +563,18 @@ OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult)
 static OCStackResult
 HandleVirtualResource (OCServerRequest *request, OCResource* resource)
 {
+    if(!request || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     char *filterValue = NULL;
     uint8_t filterOn = 0;
     uint16_t remaining = 0;
-    unsigned char * ptr = NULL;
+    char * ptr = NULL;
     uint8_t firstLoopDone = 0;
-    unsigned char discoveryResBuf[MAX_RESPONSE_LENGTH] = {0};
+    char discoveryResBuf[MAX_RESPONSE_LENGTH] = {};
 
     OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource"));
 
@@ -545,7 +626,7 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
 
             if(strlen((const char *)discoveryResBuf) > 0)
             {
-                OCEntityHandlerResponse response = {0};
+                OCEntityHandlerResponse response = {};
 
                 response.ehResult = OC_EH_OK;
                 response.payload = discoveryResBuf;
@@ -600,15 +681,21 @@ HandleVirtualResource (OCServerRequest *request, OCResource* resource)
 static OCStackResult
 HandleDefaultDeviceEntityHandler (OCServerRequest *request)
 {
+    if(!request)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_OK;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler"));
     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
             request->method, (OCResourceHandle) NULL, request->query,
             request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions,
-            request->rcvdVendorSpecificHeaderOptions, (OCObserveAction)request->observationOption, (OCObservationId)0);
+            request->rcvdVendorSpecificHeaderOptions,
+            (OCObserveAction)request->observationOption, (OCObservationId)0);
     VERIFY_SUCCESS(result, OC_STACK_OK);
 
     // At this point we know for sure that defaultDeviceHandler exists
@@ -633,12 +720,17 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
                                  OCResource *resource,
                                  uint8_t collectionResource)
 {
+    if(!request || ! resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
     OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG;
     ResourceObserver *resObs = NULL;
 
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler"));
     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
@@ -666,7 +758,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
                 &request->addressInfo, request->connectivityType);
         if(result == OC_STACK_OK)
         {
-            OC_LOG(DEBUG, TAG, PCF("Added observer successfully"));
+            OC_LOG(INFO, TAG, PCF("Added observer successfully"));
             request->observeResult = OC_STACK_OK;
             ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG);
         }
@@ -674,7 +766,7 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
         {
             result = OC_STACK_OK;
             request->observeResult = OC_STACK_ERROR;
-            OC_LOG(DEBUG, TAG, PCF("Observer Addition failed"));
+            OC_LOG(ERROR, TAG, PCF("Observer Addition failed"));
             ehFlag = OC_REQUEST_FLAG;
         }
 
@@ -700,14 +792,14 @@ HandleResourceWithEntityHandler (OCServerRequest *request,
 
         if(result == OC_STACK_OK)
         {
-            OC_LOG(DEBUG, TAG, PCF("Removed observer successfully"));
+            OC_LOG(INFO, TAG, PCF("Removed observer successfully"));
             request->observeResult = OC_STACK_OK;
         }
         else
         {
             result = OC_STACK_OK;
             request->observeResult = OC_STACK_ERROR;
-            OC_LOG(DEBUG, TAG, PCF("Observer Removal failed"));
+            OC_LOG(ERROR, TAG, PCF("Observer Removal failed"));
         }
     }
     else
@@ -735,8 +827,13 @@ static OCStackResult
 HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request,
                                               OCResource *resource)
 {
+    if(!request || !resource)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request,
             request->method, (OCResourceHandle) resource, request->query,
@@ -820,41 +917,42 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
     cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_HREF,
             cJSON_CreateString(GetVirtualResourceUri(OC_DEVICE_URI)));
 
-    cJSON_AddItemToObject (savedDeviceInfo, "rep", repObj = cJSON_CreateObject());
+    cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_REPRESENTATION, repObj = cJSON_CreateObject());
 
     if (deviceInfo.contentType)
     {
-        cJSON_AddItemToObject (repObj, "ct",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_CONTENT_TYPE,
                 cJSON_CreateString(deviceInfo.contentType));
     }
 
     if (deviceInfo.dateOfManufacture)
     {
-        cJSON_AddItemToObject (repObj, "mndt",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_DATE,
                 cJSON_CreateString(deviceInfo.dateOfManufacture));
     }
 
     if (deviceInfo.deviceName)
     {
-        cJSON_AddItemToObject (repObj, "dn",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_NAME,
                 cJSON_CreateString(deviceInfo.deviceName));
     }
 
     if (deviceInfo.deviceUUID)
     {
-        cJSON_AddItemToObject (repObj, "di",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_DEVICE_ID,
                 cJSON_CreateString(deviceInfo.deviceUUID));
     }
 
     if (deviceInfo.firmwareVersion)
     {
-        cJSON_AddItemToObject (repObj, "mnfv",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_FW_VERSION,
                 cJSON_CreateString(deviceInfo.firmwareVersion));
     }
 
     if (deviceInfo.hostName)
     {
-        cJSON_AddItemToObject (repObj, "hn", cJSON_CreateString(deviceInfo.hostName));
+        cJSON_AddItemToObject (repObj, OC_RSRVD_HOST_NAME,
+                cJSON_CreateString(deviceInfo.hostName));
     }
 
     if (deviceInfo.manufacturerName)
@@ -865,7 +963,7 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
             return OC_STACK_INVALID_PARAM;
         }
 
-        cJSON_AddItemToObject (repObj, "mnmn",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_NAME,
                 cJSON_CreateString(deviceInfo.manufacturerName));
     }
 
@@ -877,34 +975,35 @@ OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo)
             return OC_STACK_INVALID_PARAM;
         }
 
-        cJSON_AddItemToObject (repObj, "mnml",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MFG_URL,
                 cJSON_CreateString(deviceInfo.manufacturerUrl));
     }
 
     if (deviceInfo.modelNumber)
     {
-        cJSON_AddItemToObject (repObj, "mnmo",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_MODEL_NUM,
                 cJSON_CreateString(deviceInfo.modelNumber));
     }
 
     if (deviceInfo.platformVersion)
     {
-        cJSON_AddItemToObject (repObj, "mnpv",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_PLATFORM_VERSION,
                 cJSON_CreateString(deviceInfo.platformVersion));
     }
 
     if (deviceInfo.supportUrl)
     {
-        cJSON_AddItemToObject (repObj, "mnsl",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_SUPPORT_URL,
                 cJSON_CreateString(deviceInfo.supportUrl));
     }
 
     if (deviceInfo.version)
     {
-        cJSON_AddItemToObject (repObj, "icv",
+        cJSON_AddItemToObject (repObj, OC_RSRVD_VERSION,
                 cJSON_CreateString(deviceInfo.version));
     }
 
     return OC_STACK_OK;
 }
 
+
index 5574826..8abdf51 100644 (file)
@@ -40,6 +40,12 @@ static struct OCServerResponse * serverResponseList = NULL;
 
 OCServerRequest * GetServerRequestUsingToken (const CAToken_t token)
 {
+    if(!token)
+    {
+        OC_LOG(ERROR, TAG, PCF("Invalid Parameter Token"));
+        return NULL;
+    }
+
     OCServerRequest * out = NULL;
     LL_FOREACH (serverRequestList, out)
     {
@@ -51,7 +57,7 @@ OCServerRequest * GetServerRequestUsingToken (const CAToken_t token)
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
     return NULL;
 }
 
@@ -65,7 +71,7 @@ OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle)
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Request not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Request not found!!"));
     return NULL;
 }
 
@@ -79,17 +85,17 @@ OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle)
             return out;
         }
     }
-    OC_LOG(INFO, TAG, PCF("Server Response not found!!"));
+    OC_LOG(ERROR, TAG, PCF("Server Response not found!!"));
     return NULL;
 }
 
 OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
         uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method,
         uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption,
-        OCQualityOfService qos, unsigned char * query,
+        OCQualityOfService qos, char * query,
         OCHeaderOption * rcvdVendorSpecificHeaderOptions,
-        unsigned char * reqJSONPayload, CAToken_t * requestToken,
-        unsigned char * resourceUrl, size_t reqTotalSize,
+        char * reqJSONPayload, CAToken_t * requestToken,
+        char * resourceUrl, size_t reqTotalSize,
         CAAddress_t *addressInfo, CAConnectivityType_t connectivityType)
 {
     OCServerRequest * serverRequest = NULL;
@@ -136,8 +142,8 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID,
     {
         serverRequest->requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
         VERIFY_NON_NULL (serverRequest->requestToken);
-        memset(serverRequest->requestToken, 0, CA_MAX_TOKEN_LEN + 1);
         memcpy(serverRequest->requestToken, *requestToken, CA_MAX_TOKEN_LEN);
+        serverRequest->requestToken[CA_MAX_TOKEN_LEN]='\0';
     }
 
     if(resourceUrl)
@@ -174,9 +180,8 @@ OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle r
     serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse));
     VERIFY_NON_NULL(serverResponse);
 
-    serverResponse->payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH);
+    serverResponse->payload = (char *) OCCalloc(1, MAX_RESPONSE_LENGTH);
     VERIFY_NON_NULL(serverResponse->payload);
-    memset(serverResponse->payload, 0, MAX_RESPONSE_LENGTH);
 
     serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH;
     serverResponse->requestHandle = requestHandle;
@@ -202,8 +207,8 @@ OCStackResult FormOCEntityHandlerRequest(
         OCRequestHandle request,
         OCMethod method,
         OCResourceHandle resource,
-        unsigned char * queryBuf,
-        unsigned char * bufReqPayload,
+        char * queryBuf,
+        char * bufReqPayload,
         uint8_t numVendorOptions,
         OCHeaderOption * vendorOptions,
         OCObserveAction observeAction,
@@ -342,13 +347,12 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
             break;
     }
 
-    responseInfo.info.token = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
+    responseInfo.info.token = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
     if (!responseInfo.info.token)
     {
         OC_LOG(FATAL, TAG, "Response Info Token is NULL");
         return result;
     }
-    memset(responseInfo.info.token, 0, CA_MAX_TOKEN_LEN + 1);
     memcpy(responseInfo.info.token, serverRequest->requestToken, CA_MAX_TOKEN_LEN);
 
     if(serverRequest->observeResult == OC_STACK_OK)
@@ -361,15 +365,10 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse)
     }
 
     responseInfo.info.options = (CAHeaderOption_t *)
-                                    malloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
+                                  OCMalloc(sizeof(CAHeaderOption_t) * responseInfo.info.numOptions);
 
     optionsPointer = responseInfo.info.options;
 
-    if(serverRequest->observeResult == OC_STACK_OK)
-    {
-        responseInfo.info.numOptions = ehResponse->numSendVendorSpecificHeaderOptions + 1;
-    }
-
     // TODO: This exposes CoAP specific details.  At some point, this should be
     // re-factored and handled in the CA layer.
     if(serverRequest->observeResult == OC_STACK_OK)
@@ -457,6 +456,12 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
     OCServerResponse * serverResponse = NULL;
     uint16_t bufferNeeded = 0;
 
+    if(!ehResponse || !ehResponse->payload)
+    {
+        OC_LOG(ERROR, TAG, PCF("HandleAggregateResponse invalid parameters"));
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload);
 
     serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle);
@@ -486,7 +491,7 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         }
         if(serverResponse->remainingPayloadSize >= bufferNeeded)
         {
-            OC_LOG(INFO, TAG, PCF("There is room in response buffer"));
+            OC_LOG(ERROR, TAG, PCF("There is room in response buffer"));
             // append
             strncat((char *)serverResponse->payload,
                     (char *)ehResponse->payload,
@@ -517,7 +522,7 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
         }
         else
         {
-            OC_LOG(INFO, TAG, PCF("No room in response buffer"));
+            OC_LOG(ERROR, TAG, PCF("No room in response buffer"));
             //Delete the request and response
             FindAndDeleteServerRequest(serverRequest);
             FindAndDeleteServerResponse(serverResponse);
@@ -527,3 +532,4 @@ OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse)
 exit:
     return stackRet;
 }
+
index c0eaf2c..47eafdd 100644 (file)
@@ -78,9 +78,9 @@ static uint8_t PresenceTimeOutSize = 0;
 static uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100};
 #endif
 
-OCMode myStackMode;
+static OCMode myStackMode;
 OCDeviceEntityHandler defaultDeviceHandler;
-OCStackResult getQueryFromUri(const char * uri, unsigned char** resourceType, char ** newURI);
+OCStackResult getQueryFromUri(const char * uri, char** resourceType, char ** newURI);
 
 //-----------------------------------------------------------------------------
 // Macros
@@ -109,11 +109,11 @@ static uint32_t GetTime(float afterSeconds)
 static OCStackResult FormOCResponse(OCResponse * * responseLoc,
                                     ClientCB * cbNode,
                                     uint32_t maxAge,
-                                    unsigned char * fullUri,
-                                    unsigned char * rcvdUri,
+                                    char * fullUri,
+                                    char * rcvdUri,
                                     CAToken_t * rcvdToken,
                                     OCClientResponse * clientResponse,
-                                    unsigned char * bufRes)
+                                    char * bufRes)
 {
     OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse));
     if (!response)
@@ -135,12 +135,12 @@ static OCStackResult FormOCResponse(OCResponse * * responseLoc,
 /// This method is used to create the IPv4 dev_addr structure.
 /// TODO: Remove in future. Temporary helper function.
 /// Builds a socket interface address using IP address and port number
-static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
+static OCStackResult OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
         uint16_t port, OCDevAddr *ipAddr)
 {
     if ( !ipAddr ) {
-        OC_LOG(FATAL, TAG, "Invalid argument");
-        return 1;
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
+        return OC_STACK_INVALID_PARAM;
     }
 
     ipAddr->addr[0] = a;
@@ -149,7 +149,7 @@ static int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d,
     ipAddr->addr[3] = d;
     *((uint16_t*)&(ipAddr->addr[4])) = port;
 
-    return 0;
+    return OC_STACK_OK;
 }
 
 //-----------------------------------------------------------------------------
@@ -162,7 +162,7 @@ OCStackResult OCStackFeedBack(CAToken_t * token, uint8_t status)
 {
     OCStackResult result = OC_STACK_ERROR;
     ResourceObserver * observer = NULL;
-    OCEntityHandlerRequest ehRequest = {0};
+    OCEntityHandlerRequest ehRequest = {};
 
     switch(status)
     {
@@ -342,7 +342,7 @@ OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectiv
 OCStackResult UpdateResponseAddr(OCClientResponse *response, const CARemoteEndpoint_t* endPoint)
 {
     OCStackResult ret = OC_STACK_ERROR;
-    static OCDevAddr address = {0};
+    static OCDevAddr address = {};
     char * tok = NULL;
     char * savePtr = NULL;
     char * cpAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
@@ -386,7 +386,7 @@ exit:
 void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, char** resType)
 {
     char * tok = NULL;
-    char * savePtr;
+    char * savePtr = NULL;
     // The format of the payload is {"oc":[%u:%u:%s]}
     // %u : sequence number,
     // %u : max age
@@ -410,7 +410,7 @@ void parsePresencePayload(char* payload, uint32_t* seqNum, uint32_t* maxAge, cha
         }
         payload[strlen((char *)payload)] = ':';
         strcpy(*resType, tok);
-        OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", *resType);
+        OC_LOG_V(DEBUG, TAG, "resourceTypeName %s", *resType);
     }
     payload[strlen((char *)payload)] = ']';
 }
@@ -447,7 +447,8 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         goto exit;
     }
 
-    ipAddress = (char *) OCMalloc(strlen(endPoint->addressInfo.IP.ipAddress) + 1);
+    size_t addressLen = strlen(endPoint->addressInfo.IP.ipAddress);
+    ipAddress = (char *) OCMalloc(addressLen + 1);
 
     if(NULL == ipAddress)
     {
@@ -456,14 +457,13 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         goto exit;
     }
 
-    strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress,
-                            strlen(endPoint->addressInfo.IP.ipAddress));
-    ipAddress[strlen(endPoint->addressInfo.IP.ipAddress)] = '\0';
+    strncpy(ipAddress, endPoint->addressInfo.IP.ipAddress, addressLen);
+    ipAddress[addressLen] = '\0';
 
     snprintf(fullUri, MAX_URI_LENGTH, "coap://%s:%u%s", ipAddress, endPoint->addressInfo.IP.port,
                 OC_PRESENCE_URI);
 
-    cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
+    cbNode = GetClientCB(NULL, NULL, fullUri);
 
     if(cbNode)
     {
@@ -472,7 +472,7 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
     else
     {
         snprintf(fullUri, MAX_URI_LENGTH, "%s%s", OC_MULTICAST_IP, endPoint->resourceUri);
-        cbNode = GetClientCB(NULL, NULL, (unsigned char *) fullUri);
+        cbNode = GetClientCB(NULL, NULL, fullUri);
         if(cbNode)
         {
             multicastPresenceSubscribe = 1;
@@ -481,8 +481,7 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
 
     if(!presenceSubscribe && !multicastPresenceSubscribe)
     {
-        OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \
-                                                ------------ ignoring"));
+        OC_LOG(ERROR, TAG, PCF("Received a presence notification, but no callback, ignoring"));
         goto exit;
     }
 
@@ -511,7 +510,6 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
             OC_LOG(INFO, TAG, PCF("===============No presence change"));
             goto exit;
         }
-
         if(maxAge == 0)
         {
             OC_LOG(INFO, TAG, PCF("===============Stopping presence"));
@@ -528,7 +526,6 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
             if(!cbNode->presence)
             {
                 cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence));
-
                 if(!(cbNode->presence))
                 {
                     OC_LOG(ERROR, TAG, PCF("Could not allocate memory for cbNode->presence"));
@@ -583,13 +580,13 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         // This is the multicast case
 
         OCMulticastNode* mcNode = NULL;
-        mcNode = GetMCPresenceNode((const unsigned char *)fullUri);
+        mcNode = GetMCPresenceNode(fullUri);
 
         if(mcNode != NULL)
         {
             if(mcNode->nonce == response.sequenceNumber)
             {
-                OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)"));
+                OC_LOG(INFO, TAG, PCF("No presence change (Multicast)"));
                 goto exit;
             }
             mcNode->nonce = response.sequenceNumber;
@@ -602,24 +599,24 @@ OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint,
         }
         else
         {
-            uint32_t uriLen = strlen((char*)fullUri);
-            unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1);
+            uint32_t uriLen = strlen(fullUri);
+            char* uri = (char *) OCMalloc(uriLen + 1);
             if(uri)
             {
                 memcpy(uri, fullUri, (uriLen + 1));
             }
             else
             {
-                OC_LOG(INFO, TAG,
-                    PCF("===============No Memory for URI to store in the presence node"));
+                OC_LOG(ERROR, TAG,
+                    PCF("No Memory for URI to store in the presence node"));
                 result = OC_STACK_NO_MEMORY;
                 goto exit;
             }
-            result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, response.sequenceNumber);
+            result = AddMCPresenceNode(&mcNode, uri, response.sequenceNumber);
             if(result == OC_STACK_NO_MEMORY)
             {
-                OC_LOG(INFO, TAG,
-                    PCF("===============No Memory for Multicast Presence Node"));
+                OC_LOG(ERROR, TAG,
+                    PCF("No Memory for Multicast Presence Node"));
                 result = OC_STACK_NO_MEMORY;
                 OCFree(uri);
                 goto exit;
@@ -656,8 +653,6 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
 {
     OC_LOG(INFO, TAG, PCF("Enter HandleCAResponses"));
 
-    OCStackApplicationResult appResult = OC_STACK_DELETE_TRANSACTION;
-
     if(NULL == endPoint)
     {
         OC_LOG(ERROR, TAG, PCF("endPoint is NULL"));
@@ -676,7 +671,7 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
         return;
     }
 
-    ClientCB *cbNode = GetClientCB((CAToken_t *)&(responseInfo->info.token), NULL, NULL);
+    ClientCB *cbNode = GetClientCB(&(responseInfo->info.token), NULL, NULL);
 
     if (cbNode)
     {
@@ -691,7 +686,7 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
         }
 
         response.result = CAToOCStackResult(responseInfo->result);
-        response.resJSONPayload = (unsigned char*)responseInfo->info.payload;
+        response.resJSONPayload = responseInfo->info.payload;
         response.numRcvdVendorSpecificHeaderOptions = 0;
         if(responseInfo->info.options && responseInfo->info.numOptions > 0)
         {
@@ -721,9 +716,8 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_
                  &(responseInfo->info.options[i]), sizeof(OCHeaderOption));
             }
         }
-        appResult = cbNode->callBack(cbNode->context,
-                cbNode->handle, &response);
-        if (appResult == OC_STACK_DELETE_TRANSACTION)
+        if (cbNode->callBack(cbNode->context,cbNode->handle, &response)
+                == OC_STACK_DELETE_TRANSACTION)
         {
             FindAndDeleteClientCB(cbNode);
         }
@@ -760,8 +754,8 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
 
     OC_LOG_V(INFO, TAG, PCF("***** Endpoint URI ***** : %s\n"), (char*)endPoint->resourceUri);
 
-    char * newUri = (char *)endPoint->resourceUri;
-    unsigned char * query = NULL;
+    char * newUri = NULL;
+    char * query = NULL;
     getQueryFromUri(endPoint->resourceUri, &query, &newUri);
     OC_LOG_V(INFO, TAG, PCF("**********URI without query ****: %s\n"), newUri);
     OC_LOG_V(INFO, TAG, PCF("**********Query ****: %s\n"), query);
@@ -791,14 +785,15 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     //copy request payload
     if (requestInfo->info.payload)
     {
-        serverRequest.reqTotalSize = strlen(requestInfo->info.payload) + 1;
+        size_t payloadLen = strlen(requestInfo->info.payload);
+        serverRequest.reqTotalSize = payloadLen + 1;
         memcpy (&(serverRequest.reqJSONPayload), requestInfo->info.payload,
-                strlen(requestInfo->info.payload));
-        serverRequest.reqTotalSize = strlen((const char *)requestInfo->info.payload) + 1;
+                payloadLen);
     }
     else
     {
         serverRequest.reqTotalSize = 1;
+        serverRequest.reqJSONPayload[0] = '\0';
     }
 
     switch (requestInfo->method)
@@ -833,7 +828,7 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t*
     OC_LOG_V(INFO, TAG, "HandleCARequests: CA token length = %d", CA_MAX_TOKEN_LEN);
     OC_LOG_BUFFER(INFO, TAG, (const uint8_t *)requestInfo->info.token, CA_MAX_TOKEN_LEN);
 
-    serverRequest.requestToken = (CAToken_t)OCCalloc(1, CA_MAX_TOKEN_LEN+1);
+    serverRequest.requestToken = (CAToken_t)OCMalloc(CA_MAX_TOKEN_LEN+1);
     // Module Name
     if (!serverRequest.requestToken)
     {
@@ -924,7 +919,12 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
             OC_LOG(ERROR, TAG, PCF("Error adding server request"));
             return result;
         }
-        VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY);
+
+        if(!request)
+        {
+            OC_LOG(ERROR, TAG, PCF("Out of Memory"));
+            return OC_STACK_NO_MEMORY;
+        }
 
         if(!protocolRequest->reqMorePacket)
         {
@@ -933,7 +933,8 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
     }
     else
     {
-        OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request"));
+        OC_LOG(INFO, TAG,
+                PCF("This is either a repeated Server Request or blocked Server Request"));
     }
 
     if(request->requestComplete)
@@ -957,19 +958,19 @@ OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest)
     return result;
 }
 
-int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
+int ParseIPv4Address(char * ipAddrStr, uint8_t * ipAddr, uint16_t * port)
 {
     size_t index = 0;
-    unsigned char *itr, *coap;
+    char *itr, *coap;
     uint8_t dotCount = 0;
 
     ipAddr[index] = 0;
     *port = 0;
     /* search for scheme */
     itr = ipAddrStr;
-    if (!isdigit((unsigned char) *ipAddrStr))
+    if (!isdigit((char) *ipAddrStr))
     {
-        coap = (unsigned char *) OC_COAP_SCHEME;
+        coap = OC_COAP_SCHEME;
         while (*coap && tolower(*itr) == *coap)
         {
             coap++;
@@ -979,12 +980,12 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     ipAddrStr = itr;
 
     while (*ipAddrStr) {
-        if (isdigit((unsigned char) *ipAddrStr))
+        if (isdigit(*ipAddrStr))
         {
             ipAddr[index] *= 10;
             ipAddr[index] += *ipAddrStr - '0';
         }
-        else if ((unsigned char) *ipAddrStr == '.')
+        else if (*ipAddrStr == '.')
         {
             index++;
             dotCount++;
@@ -1000,7 +1001,7 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     {
         ipAddrStr++;
         while (*ipAddrStr){
-            if (isdigit((unsigned char) *ipAddrStr))
+            if (isdigit(*ipAddrStr))
             {
                 *port *= 10;
                 *port += *ipAddrStr - '0';
@@ -1014,8 +1015,7 @@ int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * por
     }
 
 
-    if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
-            && dotCount == 3)
+    if (dotCount == 3)
     {
         return 1;
     }
@@ -1044,13 +1044,13 @@ static OCResourceInterface *findResourceInterfaceAtIndex(
 static void deleteResourceType(OCResourceType *resourceType);
 static void deleteResourceInterface(OCResourceInterface *resourceInterface);
 static void deleteResourceElements(OCResource *resource);
-static int deleteResource(OCResource *resource);
+static OCStackResult deleteResource(OCResource *resource);
 static void deleteAllResources();
 static void incrementSequenceNumber(OCResource * resPtr);
 static OCStackResult verifyUriQueryLength(const char * inputUri,
         uint16_t uriLen);
 static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size);
-OCStackResult getResourceType(const char * query, unsigned char** resourceType);
+OCStackResult getResourceType(const char * query, char** resourceType);
 static CAResult_t OCSelectNetwork();
 
 //-----------------------------------------------------------------------------
@@ -1309,7 +1309,7 @@ OCStackResult verifyUriQueryLength(const char *inputUri, uint16_t uriLen)
  *     OC_STACK_INVALID_METHOD   - invalid resource method
  *     OC_STACK_INVALID_URI      - invalid required or reference URI
  *
- * Note: IN case of CA, when using multicast, the required URI should not contain IP address.
+ * Note: when using multicast, the required URI should not contain IP address.
  *       Instead, it just contains the URI to the resource such as "/oc/core".
  */
 OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri,
@@ -1319,21 +1319,20 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
 {
     OCStackResult result = OC_STACK_ERROR;
     ClientCB *clientCB = NULL;
-    unsigned char * requestUri = NULL;
-    unsigned char * resourceType = NULL;
-    unsigned char * query = NULL;
+    char * requestUri = NULL;
+    char * resourceType = NULL;
+    char * query = NULL;
     char * newUri = (char *)requiredUri;
     (void) referenceUri;
     CARemoteEndpoint_t* endpoint = NULL;
     CAResult_t caResult;
     CAToken_t token = NULL;
-    CAInfo_t requestData;
-    CARequestInfo_t requestInfo;
-    CAGroupEndpoint_t grpEnd = {0};
     OCDoHandle resHandle = NULL;
+    CAInfo_t requestData ={};
+    CARequestInfo_t requestInfo ={};
+    CAGroupEndpoint_t grpEnd = {};
 
     // To track if memory is allocated for additional header options
-    uint8_t hdrOptionMemAlloc = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCDoResource"));
 
@@ -1405,7 +1404,7 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
     }
 #endif // WITH_PRESENCE
 
-    requestUri = (unsigned char *) OCMalloc(uriLen + 1);
+    requestUri = (char *) OCMalloc(uriLen + 1);
     if(requestUri)
     {
         memcpy(requestUri, newUri, (uriLen + 1));
@@ -1423,8 +1422,6 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
         goto exit;
     }
 
-    memset(&requestData, 0, sizeof(CAInfo_t));
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
     switch (method)
     {
         case OC_REST_GET:
@@ -1490,7 +1487,6 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ
         {
             goto exit;
         }
-        hdrOptionMemAlloc = 1;
         requestData.numOptions = numOptions + 1;
     }
     else
@@ -1570,10 +1566,12 @@ exit:
     }
     CADestroyRemoteEndpoint(endpoint);
     OCFree(grpEnd.resourceUri);
-
-    if (hdrOptionMemAlloc)
+    if (requestData.options  && requestData.numOptions > 0)
     {
-        OCFree(requestData.options);
+        if ((method == OC_REST_OBSERVE) || (method == OC_REST_OBSERVE_ALL))
+        {
+            OCFree(requestData.options);
+        }
     }
     return result;
 }
@@ -1613,13 +1611,12 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
      */
     OCStackResult ret = OC_STACK_OK;
     CARemoteEndpoint_t* endpoint = NULL;
-    CAResult_t caResult;
-    CAInfo_t requestData;
-    CARequestInfo_t requestInfo;
-    // Track if memory is allocated for additional header options
-    uint8_t hdrOptionMemAlloc = 0;
+    CAResult_t caResult= CA_STATUS_OK;
+    CAInfo_t requestData = {};
+    CARequestInfo_t requestInfo = {};
 
-    if(!handle) {
+    if(!handle)
+    {
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -1627,7 +1624,8 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
 
     ClientCB *clientCB = GetClientCB(NULL, handle, NULL);
 
-    if(clientCB) {
+    if(clientCB)
+    {
         switch (clientCB->method)
         {
             case OC_REST_OBSERVE:
@@ -1649,9 +1647,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
                 {
                     return OC_STACK_ERROR;
                 }
-                hdrOptionMemAlloc = 1;
                 requestData.numOptions = numOptions + 1;
-                memset(&requestInfo, 0, sizeof(CARequestInfo_t));
                 requestInfo.method = CA_GET;
                 requestInfo.info = requestData;
                 // send request
@@ -1674,7 +1670,7 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption
         }
     }
     CADestroyRemoteEndpoint(endpoint);
-    if (hdrOptionMemAlloc)
+    if (requestData.numOptions > 0)
     {
         OCFree(requestData.options);
     }
@@ -1691,20 +1687,21 @@ OCStackResult OCProcessPresence()
 
     OC_LOG(INFO, TAG, PCF("Entering RequestPresence"));
     ClientCB* cbNode = NULL;
-    OCDevAddr dst;
-    OCClientResponse clientResponse;
+    OCDevAddr dst = {};
+    OCClientResponse clientResponse ={};
     OCResponse * response = NULL;
     OCStackApplicationResult cbResult = OC_STACK_DELETE_TRANSACTION;
 
-    LL_FOREACH(cbList, cbNode) {
+    LL_FOREACH(cbList, cbNode)
+    {
         if(OC_REST_PRESENCE == cbNode->method)
         {
             if(cbNode->presence)
             {
                 uint32_t now = GetTime(0);
-                OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d",
+                OC_LOG_V(DEBUG, TAG, "this TTL level %d",
                                                         cbNode->presence->TTLlevel);
-                OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now);
+                OC_LOG_V(DEBUG, TAG, "current ticks %d", now);
 
 
                 if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1))
@@ -1712,14 +1709,15 @@ OCStackResult OCProcessPresence()
                     goto exit;
                 }
 
-                if(cbNode->presence->TTLlevel < PresenceTimeOutSize){
-                    OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d",
+                if(cbNode->presence->TTLlevel < PresenceTimeOutSize)
+                {
+                    OC_LOG_V(DEBUG, TAG, "timeout ticks %d",
                             cbNode->presence->timeOut[cbNode->presence->TTLlevel]);
                 }
 
                 if(cbNode->presence->TTLlevel >= PresenceTimeOutSize)
                 {
-                    OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks"));
+                    OC_LOG(DEBUG, TAG, PCF("No more timeout ticks"));
                     if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port))
                     {
                         OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port,
@@ -1740,7 +1738,7 @@ OCStackResult OCProcessPresence()
                         // Increment the TTLLevel (going to a next state), so we don't keep
                         // sending presence notification to client.
                         cbNode->presence->TTLlevel++;
-                        OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
+                        OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
                                                 cbNode->presence->TTLlevel);
                     }
                     else
@@ -1758,12 +1756,12 @@ OCStackResult OCProcessPresence()
 
                 if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel])
                 {
-                    CAResult_t caResult;
+                    CAResult_t caResult = CA_STATUS_OK;
                     CARemoteEndpoint_t* endpoint = NULL;
-                    CAInfo_t requestData;
-                    CARequestInfo_t requestInfo;
+                    CAInfo_t requestData ={};
+                    CARequestInfo_t requestInfo = {};
 
-                    OC_LOG(DEBUG, TAG, PCF("time to test server presence =========="));
+                    OC_LOG(DEBUG, TAG, PCF("time to test server presence"));
 
                     //TODO-CA : Why CA_WIFI alone?
                     caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, CA_WIFI,
@@ -1775,11 +1773,9 @@ OCStackResult OCProcessPresence()
                         goto exit;
                     }
 
-                    memset(&requestData, 0, sizeof(CAInfo_t));
                     requestData.type = CA_MSG_NONCONFIRM;
                     requestData.token = cbNode->token;
 
-                    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
                     requestInfo.method = CA_GET;
                     requestInfo.info = requestData;
 
@@ -1792,7 +1788,7 @@ OCStackResult OCProcessPresence()
                     }
 
                     cbNode->presence->TTLlevel++;
-                    OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d",
+                    OC_LOG_V(DEBUG, TAG, "moving to TTL level %d",
                                                             cbNode->presence->TTLlevel);
                 }
             }
@@ -1856,7 +1852,7 @@ OCStackResult OCStartPresence(const uint32_t ttl)
         presenceState = OC_PRESENCE_INITIALIZED;
 
         CAAddress_t addressInfo;
-        strncpy(addressInfo.IP.ipAddress, "224.0.1.187", CA_IPADDR_SIZE);
+        strncpy(addressInfo.IP.ipAddress, OC_MULTICAST_IP, CA_IPADDR_SIZE);
         addressInfo.IP.port = 5683;
 
         //TODO make sure there is no memory leak here since another copy
@@ -1932,12 +1928,14 @@ OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo)
 {
     OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo"));
 
-    if(myStackMode == OC_CLIENT)
+    if(myStackMode ==  OC_SERVER || myStackMode == OC_CLIENT_SERVER)
+    {
+        return SaveDeviceInfo(deviceInfo);
+    }
+    else
     {
         return OC_STACK_ERROR;
     }
-
-    return SaveDeviceInfo(deviceInfo);
 }
 
 /**
@@ -1966,17 +1964,17 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
 
     OCResource *pointer = NULL;
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering OCCreateResource"));
 
     if(myStackMode == OC_CLIENT)
     {
-        return result;
+        return OC_STACK_INVALID_PARAM;
     }
     // Validate parameters
-    if(!uri || (strlen(uri) == 0))
+    if(!uri || uri[0]=='\0' || strlen(uri)>=MAX_URI_LENGTH )
     {
         OC_LOG(ERROR, TAG, PCF("URI is invalid"));
         return OC_STACK_INVALID_URI;
@@ -1988,7 +1986,8 @@ OCStackResult OCCreateResource(OCResourceHandle *handle,
         return OC_STACK_INVALID_PARAM;
     }
 
-    if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) {
+    if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0)
+    {
         resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT;
     }
 
@@ -2118,7 +2117,13 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
         uint8_t resourceProperties)
 {
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
+
+    if(!host)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     OCStackResult result = OC_STACK_ERROR;
 
     result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName,
@@ -2131,7 +2136,7 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
         str = (char *) OCMalloc(size);
         if (!str)
         {
-            return OC_STACK_ERROR;
+            return OC_STACK_NO_MEMORY;
         }
         strncpy(str, host, size);
         ((OCResource *) *handle)->host = str;
@@ -2154,8 +2159,8 @@ OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle,
 OCStackResult OCBindResource(
         OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
 {
-    OCResource *resource;
-    uint8_t i;
+    OCResource *resource = NULL;
+    uint8_t i = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCBindResource"));
 
@@ -2185,17 +2190,18 @@ OCStackResult OCBindResource(
         {
             resource->rsrcResources[i] = (OCResource *) resourceHandle;
             OC_LOG(INFO, TAG, PCF("resource bound"));
+
+            #ifdef WITH_PRESENCE
+            if(presenceResource.handle)
+            {
+                ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
+                SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+            }
+            #endif
             return OC_STACK_OK;
-        }
-    }
 
-    #ifdef WITH_PRESENCE
-    if(presenceResource.handle)
-    {
-        ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom();
-        SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
+        }
     }
-    #endif
 
     // Unable to add resourceHandle, so return error
     return OC_STACK_ERROR;
@@ -2213,9 +2219,10 @@ OCStackResult OCBindResource(
  *     OC_STACK_INVALID_PARAM - invalid collectionHandle
  */
 OCStackResult OCUnBindResource(
-        OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) {
-    OCResource *resource;
-    uint8_t i;
+        OCResourceHandle collectionHandle, OCResourceHandle resourceHandle)
+{
+    OCResource *resource = NULL;
+    uint8_t i = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource"));
 
@@ -2223,22 +2230,26 @@ OCStackResult OCUnBindResource(
     VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR);
     VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR);
     // Container cannot contain itself
-    if (collectionHandle == resourceHandle) {
+    if (collectionHandle == resourceHandle)
+    {
         OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle"));
         return OC_STACK_INVALID_PARAM;
     }
 
     // Use the handle to find the resource in the resource linked list
     resource = findResource((OCResource *) collectionHandle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Collection handle not found"));
         return OC_STACK_INVALID_PARAM;
     }
 
     // Look for an open slot to add add the child resource.
     // If found, add it and return success
-    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) {
-        if (resourceHandle == resource->rsrcResources[i]) {
+    for (i = 0; i < MAX_CONTAINED_RESOURCES; i++)
+    {
+        if (resourceHandle == resource->rsrcResources[i])
+        {
             resource->rsrcResources[i] = (OCResource *) NULL;
             OC_LOG(INFO, TAG, PCF("resource unbound"));
 
@@ -2250,7 +2261,6 @@ OCStackResult OCUnBindResource(
                 SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType);
             }
             #endif
-
             return OC_STACK_OK;
         }
     }
@@ -2266,7 +2276,7 @@ OCStackResult BindResourceTypeToResource(OCResource* resource,
 {
     OCResourceType *pointer = NULL;
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource"));
@@ -2315,7 +2325,7 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
 {
     OCResourceInterface *pointer = NULL;
     char *str = NULL;
-    size_t size;
+    size_t size = 0;
     OCStackResult result = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource"));
@@ -2370,14 +2380,16 @@ OCStackResult BindResourceInterfaceToResource(OCResource* resource,
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
-        const char *resourceTypeName) {
+        const char *resourceTypeName)
+{
 
     OCStackResult result = OC_STACK_ERROR;
-    OCResource *resource;
+    OCResource *resource = NULL;
 
     // Make sure resource exists
     resource = findResource((OCResource *) handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_ERROR;
     }
@@ -2408,14 +2420,16 @@ OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle,
  */
 
 OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
-        const char *resourceInterfaceName) {
+        const char *resourceInterfaceName)
+{
 
     OCStackResult result = OC_STACK_ERROR;
-    OCResource *resource;
+    OCResource *resource = NULL;
 
     // Make sure resource exists
     resource = findResource((OCResource *) handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_ERROR;
     }
@@ -2444,13 +2458,15 @@ OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle,
  *     OC_STACK_ERROR - stack process error
 
  */
-OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
+OCStackResult OCGetNumberOfResources(uint8_t *numResources)
+{
     OCResource *pointer = headResource;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources"));
     VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM);
     *numResources = 0;
-    while (pointer) {
+    while (pointer)
+    {
         *numResources = *numResources + 1;
         pointer = pointer->next;
     }
@@ -2466,15 +2482,15 @@ OCStackResult OCGetNumberOfResources(uint8_t *numResources) {
  *    Resource handle - if found
  *    NULL - if not found
  */
-OCResourceHandle OCGetResourceHandle(uint8_t index) {
+OCResourceHandle OCGetResourceHandle(uint8_t index)
+{
     OCResource *pointer = headResource;
-    uint8_t i = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle"));
 
     // Iterate through the list
-    while ((i < index) && pointer) {
-        i++;
+    for( uint8_t i = 0; i < index && pointer; ++i)
+    {
         pointer = pointer->next;
     }
     return (OCResourceHandle) pointer;
@@ -2492,21 +2508,25 @@ OCResourceHandle OCGetResourceHandle(uint8_t index) {
  *     OC_STACK_NO_RESOURCE     - resource not found
  *     OC_STACK_INVALID_PARAM   - invalid param
  */
-OCStackResult OCDeleteResource(OCResourceHandle handle) {
+OCStackResult OCDeleteResource(OCResourceHandle handle)
+{
     OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource"));
 
-    if (!handle) {
+    if (!handle)
+    {
         OC_LOG(ERROR, TAG, PCF("Invalid param"));
         return OC_STACK_INVALID_PARAM;
     }
 
     OCResource *resource = findResource((OCResource *) handle);
-    if (resource == NULL) {
+    if (resource == NULL)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_NO_RESOURCE;
     }
 
-    if (deleteResource((OCResource *) handle) == 0) {
+    if (deleteResource((OCResource *) handle) != OC_STACK_OK)
+    {
         OC_LOG(ERROR, TAG, PCF("Error deleting resource"));
         return OC_STACK_ERROR;
     }
@@ -2522,12 +2542,14 @@ OCStackResult OCDeleteResource(OCResourceHandle handle) {
  *    URI string - if resource found
  *    NULL - resource not found
  */
-const char *OCGetResourceUri(OCResourceHandle handle) {
-    OCResource *resource;
+const char *OCGetResourceUri(OCResourceHandle handle)
+{
+    OCResource *resource = NULL;
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri"));
 
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         return resource->uri;
     }
     return (const char *) NULL;
@@ -2540,18 +2562,20 @@ const char *OCGetResourceUri(OCResourceHandle handle) {
  *
  * @param handle - handle of resource
  * @return
- *    property bitmap - if resource found
- *    NULL - resource not found
+ *    OCResourceProperty Bitmask
+ *    -1 if resource is not found
  */
-uint8_t OCGetResourceProperties(OCResourceHandle handle) {
-    OCResource *resource;
+OCResourceProperty OCGetResourceProperties(OCResourceHandle handle)
+{
+    OCResource *resource = NULL;
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties"));
 
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         return resource->resourceProperties;
     }
-    return 0;
+    return (OCResourceProperty)-1;
 }
 
 /**
@@ -2565,9 +2589,10 @@ uint8_t OCGetResourceProperties(OCResourceHandle handle) {
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
-        uint8_t *numResourceTypes) {
-    OCResource *resource;
-    OCResourceType *pointer;
+        uint8_t *numResourceTypes)
+{
+    OCResource *resource = NULL;
+    OCResourceType *pointer = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes"));
     VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM);
@@ -2576,9 +2601,11 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
     *numResourceTypes = 0;
 
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         pointer = resource->rsrcType;
-        while (pointer) {
+        while (pointer)
+        {
             *numResourceTypes = *numResourceTypes + 1;
             pointer = pointer->next;
         }
@@ -2596,13 +2623,15 @@ OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle,
  *    resource type name - if resource found
  *    NULL - resource not found
  */
-const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
-    OCResourceType *resourceType;
+const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index)
+{
+    OCResourceType *resourceType = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName"));
 
     resourceType = findResourceTypeAtIndex(handle, index);
-    if (resourceType) {
+    if (resourceType)
+    {
         return resourceType->resourcetypename;
     }
     return (const char *) NULL;
@@ -2621,9 +2650,10 @@ const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) {
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
-        uint8_t *numResourceInterfaces) {
-    OCResourceInterface *pointer;
-    OCResource *resource;
+        uint8_t *numResourceInterfaces)
+{
+    OCResourceInterface *pointer = NULL;
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces"));
 
@@ -2632,9 +2662,11 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
 
     *numResourceInterfaces = 0;
     resource = findResource((OCResource *) handle);
-    if (resource) {
+    if (resource)
+    {
         pointer = resource->rsrcInterface;
-        while (pointer) {
+        while (pointer)
+        {
             *numResourceInterfaces = *numResourceInterfaces + 1;
             pointer = pointer->next;
         }
@@ -2652,13 +2684,15 @@ OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle,
  *    resource interface name - if resource found
  *    NULL - resource not found
  */
-const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
-    OCResourceInterface *resourceInterface;
+const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index)
+{
+    OCResourceInterface *resourceInterface = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName"));
 
     resourceInterface = findResourceInterfaceAtIndex(handle, index);
-    if (resourceInterface) {
+    if (resourceInterface)
+    {
         return resourceInterface->name;
     }
     return (const char *) NULL;
@@ -2675,17 +2709,20 @@ const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) {
  *    NULL - resource not found
  */
 OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle,
-        uint8_t index) {
-    OCResource *resource;
+        uint8_t index)
+{
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource"));
 
-    if (index >= MAX_CONTAINED_RESOURCES) {
+    if (index >= MAX_CONTAINED_RESOURCES)
+    {
         return NULL;
     }
 
     resource = findResource((OCResource *) collectionHandle);
-    if (!resource) {
+    if (!resource)
+    {
         return NULL;
     }
 
@@ -2702,18 +2739,19 @@ OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHa
  *     OC_STACK_ERROR - stack process error
  */
 OCStackResult OCBindResourceHandler(OCResourceHandle handle,
-        OCEntityHandler entityHandler) {
-    OCResource *resource;
+        OCEntityHandler entityHandler)
+{
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler"));
 
     // Validate parameters
     VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM);
-    //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM);
 
     // Use the handle to find the resource in the resource linked list
     resource = findResource((OCResource *)handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return OC_STACK_ERROR;
     }
@@ -2741,14 +2779,16 @@ OCStackResult OCBindResourceHandler(OCResourceHandle handle,
  *    entity handler - if resource found
  *    NULL - resource not found
  */
-OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) {
-    OCResource *resource;
+OCEntityHandler OCGetResourceHandler(OCResourceHandle handle)
+{
+    OCResource *resource = NULL;
 
     OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler"));
 
     // Use the handle to find the resource in the resource linked list
     resource = findResource((OCResource *)handle);
-    if (!resource) {
+    if (!resource)
+    {
         OC_LOG(ERROR, TAG, PCF("Resource not found"));
         return NULL;
     }
@@ -2841,12 +2881,13 @@ OCStackResult SendStopNotification()
  *     OC_STACK_NO_RESOURCE - invalid resource handle
  *     OC_STACK_NO_OBSERVERS - no more observers intrested in resource
  */
-OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) {
+OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos)
+{
 
     OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers"));
 
     OCResource *resPtr = NULL;
-    OCStackResult result;
+    OCStackResult result = OC_STACK_ERROR;
     OCMethod method = OC_REST_NOMETHOD;
     uint32_t maxAge = 0;
 
@@ -2884,7 +2925,7 @@ OCStackResult
 OCNotifyListOfObservers (OCResourceHandle handle,
                          OCObservationId  *obsIdList,
                          uint8_t          numberOfIds,
-                         unsigned char    *notificationJSONPayload,
+                         const char       *notificationJSONPayload,
                          OCQualityOfService qos)
 {
     OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers"));
@@ -3012,7 +3053,8 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
         OCResourceProperty resourceProperties, uint8_t enable)
 {
     if (resourceProperties
-            > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) {
+            > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW))
+    {
         OC_LOG(ERROR, TAG, PCF("Invalid property"));
         return OC_STACK_INVALID_PARAM;
     }
@@ -3031,7 +3073,8 @@ OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty,
 /**
  * Initialize resource data structures, variables, etc.
  */
-OCStackResult initResources() {
+OCStackResult initResources()
+{
     OCStackResult result = OC_STACK_OK;
     // Init application resource vars
     headResource = NULL;
@@ -3061,9 +3104,9 @@ OCStackResult initResources() {
  */
 void insertResource(OCResource *resource)
 {
-    if (!headResource)
-    {
-        // First resource. Head and tail are the same.
+    OCResource *pointer = NULL;
+
+    if (!headResource) {
         headResource = resource;
         tailResource = resource;
     }
@@ -3101,7 +3144,7 @@ OCResource *findResource(OCResource *resource)
 void deleteAllResources()
 {
     OCResource *pointer = headResource;
-    OCResource *temp;
+    OCResource *temp = NULL;
 
     while (pointer)
     {
@@ -3129,13 +3172,13 @@ void deleteAllResources()
  *
  * @param resource - resource to be deleted
  * @return
- *    0 - error
- *    1 - success
+ *    OC_STACK_ERROR - error
+ *    OC_STACK_OK - success
  */
-int deleteResource(OCResource *resource)
+OCStackResult deleteResource(OCResource *resource)
 {
     OCResource *prev = NULL;
-    OCResource *temp;
+    OCResource *temp = NULL;
 
     temp = headResource;
     while (temp)
@@ -3165,7 +3208,6 @@ int deleteResource(OCResource *resource)
                 }
             }
             #endif
-
             // Only resource in list.
             if (temp == headResource && temp == tailResource)
             {
@@ -3190,7 +3232,7 @@ int deleteResource(OCResource *resource)
 
             deleteResourceElements(temp);
             OCFree(temp);
-            return 1;
+            return OC_STACK_OK;
         }
         else
         {
@@ -3199,7 +3241,7 @@ int deleteResource(OCResource *resource)
         }
     }
 
-    return 0;
+    return OC_STACK_ERROR;
 }
 
 /**
@@ -3209,7 +3251,8 @@ int deleteResource(OCResource *resource)
  */
 void deleteResourceElements(OCResource *resource)
 {
-    if (!resource) {
+    if (!resource)
+    {
         return;
     }
 
@@ -3231,7 +3274,7 @@ void deleteResourceElements(OCResource *resource)
 void deleteResourceType(OCResourceType *resourceType)
 {
     OCResourceType *pointer = resourceType;
-    OCResourceType *next;
+    OCResourceType *next = NULL;
 
     while (pointer)
     {
@@ -3247,9 +3290,10 @@ void deleteResourceType(OCResourceType *resourceType)
  *
  * @param resourceInterface - specified resource interface
  */
-void deleteResourceInterface(OCResourceInterface *resourceInterface) {
+void deleteResourceInterface(OCResourceInterface *resourceInterface)
+{
     OCResourceInterface *pointer = resourceInterface;
-    OCResourceInterface *next;
+    OCResourceInterface *next = NULL;
 
     while (pointer)
     {
@@ -3266,8 +3310,9 @@ void deleteResourceInterface(OCResourceInterface *resourceInterface) {
  * @param resource - resource where resource type is to be inserted
  * @param resourceType - resource type to be inserted
  */
-void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
-    OCResourceType *pointer;
+void insertResourceType(OCResource *resource, OCResourceType *resourceType)
+{
+    OCResourceType *pointer = NULL;
 
     if (resource && !resource->rsrcType)
     {
@@ -3283,7 +3328,8 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
         {
             pointer = resourceType;
         }
-        while (pointer->next) {
+        while (pointer->next)
+        {
             pointer = pointer->next;
         }
         pointer->next = resourceType;
@@ -3301,10 +3347,10 @@ void insertResourceType(OCResource *resource, OCResourceType *resourceType) {
  *    resourcetype - if found
  *    NULL - not found
  */
-OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) {
-    OCResource *resource;
-    OCResourceType *pointer;
-    uint8_t i;
+OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
+{
+    OCResource *resource = NULL;
+    OCResourceType *pointer = NULL;
 
     // Find the specified resource
     resource = findResource((OCResource *) handle);
@@ -3321,10 +3367,8 @@ OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index)
 
     // Iterate through the list
     pointer = resource->rsrcType;
-    i = 0;
-    while ((i < index) && pointer)
+    for(uint8_t i = 0; i< index && pointer; ++i)
     {
-        i++;
         pointer = pointer->next;
     }
     return pointer;
@@ -3368,8 +3412,7 @@ OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char *
 void insertResourceInterface(OCResource *resource,
         OCResourceInterface *resourceInterface)
 {
-    OCResourceInterface *pointer;
-
+    OCResourceInterface *pointer = NULL;
     if (!resource->rsrcInterface)
     {
         resource->rsrcInterface = resourceInterface;
@@ -3397,27 +3440,29 @@ void insertResourceInterface(OCResource *resource,
  *    NULL - not found
  */
 OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle,
-        uint8_t index) {
-    OCResource *resource;
-    OCResourceInterface *pointer;
-    uint8_t i = 0;
+        uint8_t index)
+{
+    OCResource *resource = NULL;
+    OCResourceInterface *pointer = NULL;
 
     // Find the specified resource
     resource = findResource((OCResource *) handle);
-    if (!resource) {
+    if (!resource)
+    {
         return NULL;
     }
 
     // Make sure a resource has a resourceinterface
-    if (!resource->rsrcInterface) {
+    if (!resource->rsrcInterface)
+    {
         return NULL;
     }
 
     // Iterate through the list
     pointer = resource->rsrcInterface;
 
-    while ((i < index) && pointer) {
-        i++;
+    for (uint8_t i = 0; i < index && pointer; ++i)
+    {
         pointer = pointer->next;
     }
     return pointer;
@@ -3463,20 +3508,20 @@ uint8_t OCIsPacketTransferRequired(const char *request, const char *response, ui
 }
 
 /**
- * Retrieves a resource type based upon a query ontains only just one
+ * Retrieves a resource type based upon a query contains only just one
  * resource attribute (and that has to be of type "rt").
  *
  * @remark This API malloc's memory for the resource type. Do not malloc resourceType
  * before passing in.
  *
- * @param query - The quert part of the URI
+ * @param query - The query part of the URI
  * @param resourceType - The resource type to be populated; pass by reference.
  *
  * @return
  *  OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL.
  *  OC_STACK_OK            - Success
  */
-OCStackResult getResourceType(const char * query, unsigned char** resourceType)
+OCStackResult getResourceType(const char * query, char** resourceType)
 {
     if(!query)
     {
@@ -3487,7 +3532,7 @@ OCStackResult getResourceType(const char * query, unsigned char** resourceType)
 
     if(strncmp(query, "rt=", 3) == 0)
     {
-        *resourceType = (unsigned char *) OCMalloc(strlen(query)-3);
+        *resourceType = (char *) OCMalloc(strlen(query)-3 + 1);
         if(!*resourceType)
         {
             result = OC_STACK_NO_MEMORY;
@@ -3500,7 +3545,7 @@ OCStackResult getResourceType(const char * query, unsigned char** resourceType)
     return result;
 }
 
-OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** newURI)
+OCStackResult getQueryFromUri(const char * uri, char** query, char ** newURI)
 {
     if(!uri)
     {
@@ -3517,21 +3562,21 @@ OCStackResult getQueryFromUri(const char * uri, unsigned char** query, char ** n
         goto exit;
     }
     strcpy(tempURI, uri);
-    char* strTokPtr;
-    leftToken = strtok_r((char *)tempURI, "?", &strTokPtr);
+    char* strTokPtr = NULL;
+    leftToken = strtok_r(tempURI, "?", &strTokPtr);
 
     //TODO-CA: This could be simplified. Clean up required.
     while(leftToken != NULL)
     {
         if(strncmp(leftToken, "rt=", 3) == 0 || strncmp(leftToken, "if=", 3) == 0)
         {
-            *query = (unsigned char *) OCMalloc(strlen(leftToken) + 1);
+            *query = (char *) OCMalloc(strlen(leftToken) + 1);
             if(!*query)
             {
                 OCFree(tempURI);
                 goto exit;
             }
-            strcpy((char *)*query, ((const char *)&leftToken[0]));
+            strcpy(*query, &leftToken[0]);
             break;
         }
         leftToken = strtok_r(NULL, "?", &strTokPtr);
@@ -3549,7 +3594,6 @@ const ServerID OCGetServerInstanceID(void)
 {
     static bool generated = false;
     static ServerID sid;
-
     if(generated)
     {
         return sid;
@@ -3567,8 +3611,8 @@ const char* OCGetServerInstanceIDString(void)
     // This will change as the representation gets switched
     // to another value
     static char buffer[11];
-    int n = sprintf(buffer, "%u", OCGetServerInstanceID());
-    if (n < 0)
+
+    if (snprintf(buffer, sizeof(buffer),"%u", OCGetServerInstanceID()) < 0)
     {
         buffer[0]='\0';
     }
@@ -3580,8 +3624,9 @@ const char* OCGetServerInstanceIDString(void)
 int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
         uint8_t *c, uint8_t *d )
 {
-    if ( !ipAddr || !a || !b || !c || !d ) {
-        OC_LOG(FATAL, TAG, "Invalid argument");
+    if ( !ipAddr || !a || !b || !c || !d )
+    {
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -3597,8 +3642,9 @@ int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b,
 /// Retrieve the IPv4 address embedded inside OCDev address data structure
 int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port)
 {
-    if ( !ipAddr || !port ) {
-        OC_LOG(FATAL, TAG, "Invalid argument");
+    if ( !ipAddr || !port )
+    {
+        OC_LOG(FATAL, TAG, PCF("Invalid argument"));
         return OC_STACK_INVALID_PARAM;
     }
 
index 2d5bde6..85d17aa 100644 (file)
@@ -42,16 +42,13 @@ typedef struct aggregatehandleinfo
     OCResource *collResource;
 
     struct aggregatehandleinfo *next;
-} ClientRequstInfo;
+} ClientRequestInfo;
 
-// unsigned int nHandleIdx = 0;
-// ClientRequstInfo g_AggregateResponseHandle[10];
+static ClientRequestInfo *clientRequestList = NULL;
 
-ClientRequstInfo *clientRequstList = NULL;
-
-void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
+void AddClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* add)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     if (*head != NULL)
     {
@@ -69,9 +66,9 @@ void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add)
     }
 }
 
-ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle)
+ClientRequestInfo* GetClientRequestInfo(ClientRequestInfo *head, OCDoHandle handle)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     tmp = head;
 
@@ -79,7 +76,6 @@ ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle
     {
         while (tmp)
         {
-//            printf("%p :: %p\n", tmp->required, handle);
             if (tmp->required == handle)
             {
                 break;
@@ -93,9 +89,9 @@ ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle
     return NULL;
 }
 
-void RemoveClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* del)
+void RemoveClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* del)
 {
-    ClientRequstInfo *tmp = NULL;
+    ClientRequestInfo *tmp = NULL;
 
     if (*head == del)
     {
@@ -175,9 +171,9 @@ void AddActionSet(OCActionSet **head, OCActionSet* node)
 
 void DeleteCapability(OCCapability *del)
 {
-    free(del->capability);
+    OCFree(del->capability);
     del->capability = NULL;
-    free(del->status);
+    OCFree(del->status);
     del->status = NULL;
 }
 
@@ -322,8 +318,14 @@ OCStackResult ExtractKeyValueFromRequest(char *request, char **key, char **value
     OCStackResult result = OC_STACK_OK;
     size_t length = 0;
 
+    if(strlen(request) <= strlen(OIC_ACTION_PREFIX))
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
     char* pRequest = (char *)request + strlen(OIC_ACTION_PREFIX);
-    char* iterToken, *iterTokenPtr;
+    char* iterToken = NULL;
+    char* iterTokenPtr = NULL;
 
     iterToken = (char *) strtok_r(pRequest, ":", &iterTokenPtr);
     length = strlen(iterToken) + 1;
@@ -359,10 +361,14 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
     OCStackResult result = OC_STACK_OK;
 
     char *iterToken = NULL, *iterTokenPtr = NULL;
-    char *descIterToken = NULL, *descIterTokenPtr = NULL;
-    char *attrIterToken = NULL, *attrIterTokenPtr = NULL;
-    char *desc = NULL, *attr = NULL;
-    char *key = NULL, *value = NULL;
+    char *descIterToken = NULL;
+    char *descIterTokenPtr = NULL;
+    char *attrIterToken = NULL;
+    char *attrIterTokenPtr = NULL;
+    char *desc = NULL;
+    char *attr = NULL;
+    char *key = NULL;
+    char *value = NULL;
 
     OCAction *action = NULL;
     OCCapability *capa = NULL;
@@ -406,7 +412,7 @@ OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
             VARIFY_PARAM_NULL(attrIterToken, result, exit)
             strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
 
-            if(strcmp(key, "uri") == 0)
+            if(strncmp(key, "uri", sizeof("uri") - 1) == 0)
             {
                 OC_LOG(INFO, TAG, PCF("Build OCAction Instance."));
 
@@ -464,17 +470,13 @@ exit:
 OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 {
     char temp[1024] = { 0 };
-    int remaining = 1023;
+    uint16_t remaining = sizeof(temp) - 1;
 
-    // OCActionSet *as = resource->actionsetHead;
-    // while(as != NULL)
-    // {
-    // printf("\n\n\nAction Set Name :: %s\n", actionset->actionsetName);
     OCAction *action = actionset->head;
 
     if (remaining >= strlen(actionset->actionsetName) + 1)
     {
-        strcat(temp, actionset->actionsetName);
+        strncat(temp, actionset->actionsetName, sizeof(temp));
         remaining -= strlen(actionset->actionsetName);
         strcat(temp, "*");
         remaining--;
@@ -486,7 +488,7 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 
     while (action != NULL)
     {
-        printf("\tURI :: %s\n", action->resourceUri);
+        OC_LOG_V(INFO, TAG, "\tURI :: %s\n", action->resourceUri);
         strcat(temp, "uri=");
         remaining -= strlen("uri=");
         strcat(temp, action->resourceUri);
@@ -497,7 +499,7 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
         OCCapability *capas = action->head;
         while (capas != NULL)
         {
-            printf("\t\t%s = %s\n", capas->capability, capas->status);
+            OC_LOG_V(INFO, TAG, "\t\t%s = %s\n", capas->capability, capas->status);
             strcat(temp, capas->capability);
             remaining -= strlen(capas->capability);
             strcat(temp, "=");
@@ -519,12 +521,14 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
             remaining--;
         }
     }
-    //     as = as->next;
-    // }
 
     *desc = (char *) OCMalloc(1024 - remaining);
+    if(!*desc)
+    {
+        return OC_STACK_NO_MEMORY;
+    }
+
     strcpy(*desc, temp);
-    // printf("\t\tPlain Text = %s(%i)\n", *desc, 1024 - remaining);
 
     return OC_STACK_OK;
 }
@@ -532,27 +536,26 @@ OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
         OCClientResponse* clientResponse)
 {
-    printf("\n\n\tcallback is called\n\n");
+    OC_LOG(INFO, TAG, PCF("\n\n\tcallback is called\n\n"));
 
-    ClientRequstInfo *info = GetClientRequestInfo(clientRequstList, handle);
+    ClientRequestInfo *info = GetClientRequestInfo(clientRequestList, handle);
 
     if (info)
     {
-        int idx;
+        uint32_t idx = 0;
 
-        unsigned char *responseJson;
-        responseJson = (unsigned char *) OCMalloc(
-                (unsigned int) (strlen((char *) clientResponse->resJSONPayload) + 1));
+        char *responseJson = (char *) OCMalloc(
+                (unsigned int) (strlen( clientResponse->resJSONPayload) + 1));
 
         // We need the body of response.
         // Copy the body from the response
-        strcpy((char *) responseJson, ((char *) clientResponse->resJSONPayload
-                + OC_JSON_PREFIX_LEN));
+        strncpy((char *) responseJson, (clientResponse->resJSONPayload
+                + OC_JSON_PREFIX_LEN), strlen(clientResponse->resJSONPayload) + 1);
         idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
         // And insert NULL at the end of body.
         (responseJson[idx]) = 0;
 
-        OCEntityHandlerResponse response = { };
+        OCEntityHandlerResponse response = { };
         response.ehResult = OC_EH_OK;
         response.payload = responseJson;
         response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
@@ -562,30 +565,25 @@ OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
 
         OCDoResponse(&response);
 
-        RemoveClientRequestInfo(&clientRequstList, info);
+        RemoveClientRequestInfo(&clientRequestList, info);
         OCFree(responseJson);
     }
 
-    // g_AggregateResponseHandle
-
     return OC_STACK_KEEP_TRANSACTION;
 }
 
 void ActionSetCD(void *context)
 {
-    // printf("\n\t\tCD is called\n");
-
-    // free( context );
 }
 
-OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16_t *remaining)
+OCStackResult BuildActionJSON(OCAction* action, char* bufferPtr, uint16_t *remaining)
 {
     OCStackResult ret = OC_STACK_ERROR;
-    cJSON *json;
-    cJSON *body;
+    cJSON *json = NULL;
+    cJSON *body = NULL;
 
-    char *jsonStr;
-    uint16_t jsonLen;
+    char *jsonStr = NULL;
+    uint16_t jsonLen = 0;
 
     OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
     json = cJSON_CreateObject();
@@ -611,29 +609,29 @@ OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16
     }
 
     cJSON_Delete(json);
-    free(jsonStr);
+    OCFree(jsonStr);
 
     return ret;
 }
 
-unsigned int GetNumOfTargetResource(OCAction *actionset)
+uint32_t GetNumOfTargetResource(OCAction *actionset)
 {
-    int numOfREsource = 0;
+    uint32_t numOfResource = 0;
 
     OCAction *pointerAction = actionset;
 
     while (pointerAction != NULL)
     {
-        numOfREsource++;
+        numOfResource++;
         pointerAction = pointerAction->next;
     }
 
-    return numOfREsource;
+    return numOfResource;
 }
 
-OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const unsigned char *action)
+OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const char *action)
 {
-    OCCallbackData cbdata = { 0 };
+    OCCallbackData cbdata = {  };
     cbdata.cb = &ActionSetCB;
     cbdata.cd = &ActionSetCD;
     cbdata.context = (void *) 0x99;
@@ -649,190 +647,187 @@ OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHa
     OCStackResult stackRet = OC_STACK_ERROR;
 
     OC_LOG(INFO, TAG, PCF("Group Action is requested."));
-    // if (stackRet == OC_STACK_OK)
-    {
-        char *doWhat = NULL;
-        char *details = NULL;
-
-        size_t bufferLength = 0;
-        unsigned char buffer[MAX_RESPONSE_LENGTH] = { 0 };
-        unsigned char *bufferPtr = NULL;
+    char *doWhat = NULL;
+    char *details = NULL;
 
-        bufferPtr = buffer;
+    size_t bufferLength = 0;
+    char buffer[MAX_RESPONSE_LENGTH] = { 0 };
+    char *bufferPtr = NULL;
 
-        OCResource * collResource = (OCResource *) ehRequest->resource;
+    bufferPtr = buffer;
 
-        char *jsonResponse;
+    OCResource * collResource = (OCResource *) ehRequest->resource;
 
-        ExtractKeyValueFromRequest((char *)ehRequest->reqJSONPayload, &doWhat, &details);
+    char *jsonResponse;
 
-        cJSON *json;
-        cJSON *format;
+    ExtractKeyValueFromRequest((char *)ehRequest->reqJSONPayload, &doWhat, &details);
 
+    cJSON *json;
+    cJSON *format;
 
-        if (method == OC_REST_PUT)
-        {
-            json = cJSON_CreateObject();
-            cJSON_AddStringToObject(json, "href", resource->uri);
-            cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
 
-            OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
+    if (method == OC_REST_PUT)
+    {
+        json = cJSON_CreateObject();
+        cJSON_AddStringToObject(json, "href", resource->uri);
+        cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
 
-            if(strcmp(doWhat, "ActionSet") == 0)
-            {
-                OCActionSet *actionSet;
-                BuildActionSetFromString(&actionSet, details);
+        OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
 
-                if(actionSet != NULL)
-                {
-                    AddActionSet(&resource->actionsetHead, actionSet);
-                    stackRet = OC_STACK_OK;
-                }
-                else
-                {
-                    stackRet = OC_STACK_ERROR;
-                }
+        if(strcmp(doWhat, "ActionSet") == 0)
+        {
+            OCActionSet *actionSet;
+            BuildActionSetFromString(&actionSet, details);
 
+            if(actionSet != NULL)
+            {
+                AddActionSet(&resource->actionsetHead, actionSet);
+                stackRet = OC_STACK_OK;
             }
-            else if (strcmp(doWhat, "DelActionSet") == 0)
+            else
             {
-                if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
-                {
-                    stackRet = OC_STACK_OK;
-                }
-                else
-                {
-                    stackRet = OC_STACK_ERROR;
-                }
+                stackRet = OC_STACK_ERROR;
             }
 
-            jsonResponse = cJSON_Print(json);
-            cJSON_Delete(json);
-
-            strcat((char *) bufferPtr, jsonResponse);
-
-            bufferLength = strlen((const char *) buffer);
-            if (bufferLength > 0)
+        }
+        else if (strncmp(doWhat, "DelActionSet", sizeof("DelActionSet")) == 0)
+        {
+            if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
             {
-                OCEntityHandlerResponse response = { 0 };
-                response.ehResult = OC_EH_OK;
-                response.payload = buffer;
-                response.payloadSize = bufferLength + 1;
-                response.persistentBufferFlag = 0;
-                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
-                response.resourceHandle = (OCResourceHandle) collResource;
-                stackRet = OCDoResponse(&response);
+                stackRet = OC_STACK_OK;
+            }
+            else
+            {
+                stackRet = OC_STACK_ERROR;
             }
-
-            stackRet = OC_STACK_OK;
         }
 
-        if (method == OC_REST_POST)
+        jsonResponse = cJSON_Print(json);
+        cJSON_Delete(json);
+
+        strcat((char *) bufferPtr, jsonResponse);
+
+        bufferLength = strlen((const char *) buffer);
+        if (bufferLength > 0)
         {
-            OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
+            OCEntityHandlerResponse response = { 0 };
+            response.ehResult = OC_EH_OK;
+            response.payload = buffer;
+            response.payloadSize = bufferLength + 1;
+            response.persistentBufferFlag = 0;
+            response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+            response.resourceHandle = (OCResourceHandle) collResource;
+            stackRet = OCDoResponse(&response);
+        }
 
-            OCActionSet *actionset = NULL;
+        stackRet = OC_STACK_OK;
+    }
 
-            json = cJSON_CreateObject();
-            cJSON_AddStringToObject(json, "href", resource->uri);
+    if (method == OC_REST_POST)
+    {
+        OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
 
-            if (strcmp(doWhat, "DoAction") == 0)
-            {
-                if (GetActionSet(details, resource->actionsetHead, &actionset) != OC_STACK_OK)
-                {
-                    OC_LOG(INFO, TAG, PCF("ERROR"));
-                    stackRet = OC_STACK_ERROR;
-                }
+        OCActionSet *actionset = NULL;
 
-                if (actionset == NULL)
-                {
-                    OC_LOG(INFO, TAG, PCF("ERROR"));
-                    stackRet = OC_STACK_ERROR;
-                }
-                else
-                {
+        json = cJSON_CreateObject();
+        cJSON_AddStringToObject(json, "href", resource->uri);
 
-                    OCAction *pointerAction = actionset->head;
+        if (strcmp(doWhat, "DoAction") == 0)
+        {
+            if (GetActionSet(details, resource->actionsetHead, &actionset) != OC_STACK_OK)
+            {
+                OC_LOG(INFO, TAG, PCF("ERROR"));
+                stackRet = OC_STACK_ERROR;
+            }
 
-                    unsigned int num = GetNumOfTargetResource(pointerAction);
+            if (actionset == NULL)
+            {
+                OC_LOG(INFO, TAG, PCF("ERROR"));
+                stackRet = OC_STACK_ERROR;
+            }
+            else
+            {
 
-                    ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
-                            HandleAggregateResponse;
-                    ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
+                OCAction *pointerAction = actionset->head;
 
-                    while (pointerAction != NULL)
-                    {
-                        unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
-                        unsigned char* actionDescPtr = actionDesc;
-                        uint16_t remaining = MAX_RESPONSE_LENGTH;
+                uint32_t num = GetNumOfTargetResource(pointerAction);
 
-                        strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
-                            strlen((const char *) OC_JSON_PREFIX) + 1);
-                        BuildActionJSON(pointerAction, actionDescPtr, &remaining);
-                        strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
-                            strlen((const char *) OC_JSON_SUFFIX));
+                ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
+                        HandleAggregateResponse;
+                ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1;
 
-                        ClientRequstInfo *info = (ClientRequstInfo *) OCMalloc(
-                                sizeof(ClientRequstInfo));
-                        memset(info, 0, sizeof(ClientRequstInfo));
+                while (pointerAction != NULL)
+                {
+                    char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
+                    char* actionDescPtr = actionDesc;
+                    uint16_t remaining = MAX_RESPONSE_LENGTH;
 
-                        info->collResource = resource;
-                        info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
+                    strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
+                        strlen((const char *) OC_JSON_PREFIX) + 1);
+                    BuildActionJSON(pointerAction, actionDescPtr, &remaining);
+                    strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
+                        strlen((const char *) OC_JSON_SUFFIX));
 
-                        SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
+                    ClientRequestInfo *info = (ClientRequestInfo *) OCMalloc(
+                            sizeof(ClientRequestInfo));
+                    memset(info, 0, sizeof(ClientRequestInfo));
 
-                        AddClientRequestInfo(&clientRequstList, info);
+                    info->collResource = resource;
+                    info->ehRequest = (OCServerRequest *) ehRequest->requestHandle;
 
-                        pointerAction = pointerAction->next;
-                    }
+                    SendAction(&info->required, pointerAction->resourceUri, actionDescPtr);
 
+                    AddClientRequestInfo(&clientRequestList, info);
 
-                    stackRet = OC_STACK_OK;
+                    pointerAction = pointerAction->next;
                 }
+
+
+                stackRet = OC_STACK_OK;
             }
-            else if (strcmp(doWhat, "GetActionSet") == 0)
+        }
+        else if (strcmp(doWhat, "GetActionSet") == 0)
+        {
+            char *plainText = NULL;
+            OCActionSet *actionset = NULL;
+
+            cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
+            GetActionSet(details, resource->actionsetHead, &actionset);
+            if (actionset != NULL)
             {
-                char *plainText = NULL;
-                OCActionSet *actionset = NULL;
+                BuildStringFromActionSet(actionset, &plainText);
 
-                cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
-                GetActionSet(details, resource->actionsetHead, &actionset);
-                if (actionset != NULL)
+                if (plainText != NULL)
                 {
-                    BuildStringFromActionSet(actionset, &plainText);
-
-                    if (plainText != NULL)
-                    {
-                        cJSON_AddStringToObject(format, "ActionSet", plainText);
-                    }
-
-                    stackRet = OC_STACK_OK;
+                    cJSON_AddStringToObject(format, "ActionSet", plainText);
                 }
+
+                stackRet = OC_STACK_OK;
             }
+        }
 
-            jsonResponse = cJSON_Print(json);
-            cJSON_Delete(json);
+        jsonResponse = cJSON_Print(json);
+        cJSON_Delete(json);
 
-            strcat((char *) bufferPtr, jsonResponse);
+        strcat((char *) bufferPtr, jsonResponse);
 
-            bufferLength = strlen((const char *) buffer);
-            if (bufferLength > 0)
-            {
-                OCEntityHandlerResponse response =
-                { 0 };
-                response.ehResult = OC_EH_OK;
-                response.payload = buffer;
-                response.payloadSize = bufferLength + 1;
-                response.persistentBufferFlag = 0;
-                response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
-                response.resourceHandle = (OCResourceHandle) collResource;
-                stackRet = OCDoResponse(&response);
-            }
+        bufferLength = strlen((const char *) buffer);
+        if (bufferLength > 0)
+        {
+            OCEntityHandlerResponse response = {};
+            response.ehResult = OC_EH_OK;
+            response.payload = buffer;
+            response.payloadSize = bufferLength + 1;
+            response.persistentBufferFlag = 0;
+            response.requestHandle = (OCRequestHandle) ehRequest->requestHandle;
+            response.resourceHandle = (OCResourceHandle) collResource;
+            stackRet = OCDoResponse(&response);
         }
-
-        OCFree(doWhat);
-        OCFree(details);
     }
 
+    OCFree(doWhat);
+    OCFree(details);
+
     return stackRet;
 }
+
index 4db2ba0..7da8c21 100644 (file)
@@ -22,7 +22,7 @@ ocstack.c.  It is not a system or end-to-end test.
 Unit Test Requirements:
 
 1. Install Google Test on a Linux build machine
-2. Create a file called "local.properties" in the 
+2. Create a file called "local.properties" in the
    root/csdk/stack/test.  local.properties is used
    by the makefile and specifies the path to the
    Google Test directory on the build machine.
@@ -31,7 +31,7 @@ Unit Test Requirements:
 
    local.properties should contain GTEST_DIR.
    For example:
-   
+
 
    GTEST_DIR := /home/johndoe/utils/gtest-1.7.0
 
@@ -40,7 +40,7 @@ Unit Test Requirements:
    If no interface is available, the unit tests will FAIL.
 4. To run the unit test, first build the C OCStack.
    At the time of this writing this was done by running
-   
+
    root/csdk/make deepclean
    root/csdk/make BUILD=release    *default
    root/csdk/make BUILD=debug
@@ -54,3 +54,4 @@ Unit Test Requirements:
    root/csdk/stack/test/release/stacktests
    root/csdk/stack/test/debug/stacktests
 
+
index 87aa8a0..fe38e51 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 Import('env')
 import os
 import os.path
index 0a75156..66aa0c0 100644 (file)
@@ -23,3 +23,4 @@ LOCAL_SRC_FILES += ocstack.c
 LOCAL_SRC_FILES += stacktests.cpp
 
 
+
index 2345e08..3f51a4f 100644 (file)
@@ -32,3 +32,4 @@ PROGMEM
 "warning: only initialized variables can be placed into program memory area"
 This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734
 
+
index 2f0d389..4314f45 100644 (file)
@@ -109,3 +109,4 @@ clean:
        rm -fr $(BIN_DIR)
        rm -fr $(OBJ_DIR)
 
+
index ce5b4fd..dc8be91 100644 (file)
@@ -16,8 +16,8 @@ void ocInitialize () {
 }
 
 void setup() {
-       Serial.begin(115200);
-   
+    Serial.begin(115200);
+
     Serial.println ("Trying to get an IP addr using DHCP");
     if (Ethernet.begin(ETHERNET_MAC) == 0) {
         Serial.println("DHCP failed");
@@ -26,7 +26,8 @@ void setup() {
 }
 
 void loop() {
-       Serial.println ("Processing CoAP messages!\n");
+    Serial.println ("Processing CoAP messages!\n");
     OCProcess ();
-       delay(1000);
+    delay(1000);
 }
+
index d3861d6..e0a1500 100644 (file)
@@ -95,3 +95,4 @@ endif
 clean:
        rm -rf debug
        rm -rf release
+
index 42c739d..322b487 100644 (file)
@@ -53,8 +53,6 @@ OCStackApplicationResult applicationDiscoverCB(
 }
 
 int main() {
-    OCDoHandle handle;
-
     OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
 
     /* Initialize OCStack*/
@@ -66,7 +64,7 @@ int main() {
     /* Start a discovery query*/
     char szQueryUri[64] = { 0 };
     strcpy(szQueryUri, OC_EXPLICIT_DEVICE_DISCOVERY_URI);
-    if (OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
+    if (OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS,
             0, 0, 0) != OC_STACK_OK) {
         OC_LOG(ERROR, TAG, "OCStack resource error");
         return 0;
@@ -91,3 +89,4 @@ int main() {
 
     return 0;
 }
+
index 279815d..3813637 100644 (file)
@@ -94,3 +94,4 @@ OCStackResult createLightResource() {
                     OC_DISCOVERABLE|OC_OBSERVABLE);
     return res;
 }
+
index 493b34e..b195cf4 100644 (file)
@@ -95,3 +95,4 @@ clean: legacy_clean
 
 legacy_clean:
        rm -f *.o $(PROGRAMS)
+
index a7165cf..63dbe04 100644 (file)
@@ -1225,55 +1225,3 @@ TEST(StackResourceAccess, DeleteMiddleResource)
     EXPECT_EQ(OC_STACK_OK, OCStop());
 }
 
-#if 0
-TEST(StackTest, StackTestResourceDiscoverIfFilteringBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-    char uri[] = "/oc/core";
-    char query[] = "if";
-    char req[1024] = {};
-    char rsp[1024] = {};
-    //OCServerRequestResult res;
-
-    //EXPECT_EQ(OC_STACK_INVALID_QUERY, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-
-TEST(StackTest, StackTestResourceDiscoverRtFilteringBad) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-    char uri[] = "/oc/core";
-    char query[] = "rt";
-    char req[1024] = {};
-    char rsp[1024] = {};
-    //OCServerRequestResult res;
-
-    //EXPECT_EQ(OC_STACK_INVALID_QUERY, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-TEST(StackTest, StackTestResourceDiscoverIfFiltering) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-    char uri[] = "/oc/core";
-    char query[] = "if=oc.mi.ll";
-    char req[1024] = {};
-    char rsp[1024] = {};
-    //OCServerRequestResult res;
-
-    //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-
-TEST(StackTest, StackTestResourceDiscoverRtFiltering) {
-    uint8_t addr[20];
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
-    char uri[] = "/oc/core";
-    char query[] = "rt=core.brightled";
-    char req[1024] = {};
-    char rsp[1024] = {};
-    //OCServerRequestResult res;
-
-    //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp));
-}
-#endif
index d52f212..b72435a 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # Examples build script
 ##
@@ -30,7 +50,7 @@ if target_os not in ['windows', 'winrt']:
 
 examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap'])
-if env.get('SECURED') == '1':      
+if env.get('SECURED') == '1':
     examples_env.AppendUnique(LIBS = ['tinydtls'])
 
 examples_env.ParseConfig('pkg-config --libs glib-2.0');
@@ -81,3 +101,4 @@ Alias("examples", [simpleserver, simpleclient,
      ])
 env.AppendTarget('examples')
 
+
index 8bbb55f..20bc0aa 100644 (file)
@@ -113,7 +113,7 @@ void receivedDeviceInfo(const OCRepresentation& rep)
 
 int main(int argc, char* argv[]) {
 
-    ostringstream requestURI;
+    std::ostringstream requestURI;
     std::string deviceDiscoveryURI = "/oc/core/d";
 
     OCConnectivityType connectivityType = OC_WIFI;
@@ -123,7 +123,7 @@ int main(int argc, char* argv[]) {
         try
         {
             std::size_t inputValLen;
-            int optionSelected = stoi(argv[1], &inputValLen);
+            int optionSelected = std::stoi(argv[1], &inputValLen);
 
             if(inputValLen == strlen(argv[1]))
             {
@@ -146,7 +146,7 @@ int main(int argc, char* argv[]) {
                 std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
             }
         }
-        catch(exception& e)
+        catch(std::exception& e)
         {
             std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
         }
@@ -196,3 +196,4 @@ int main(int argc, char* argv[]) {
     return 0;
 }
 
+
index 26401ba..1474986 100644 (file)
@@ -103,7 +103,7 @@ OCStackResult SetDeviceInfo(std::string contentType, std::string dateOfManufactu
         DuplicateString(&deviceInfo.platformVersion, platformVersion);
         DuplicateString(&deviceInfo.supportUrl, supportUrl);
         DuplicateString(&deviceInfo.version, version);
-    }catch(exception &e)
+    }catch(std::exception &e)
     {
         std::cout<<"String Copy failed!!\n";
         return OC_STACK_ERROR;
@@ -171,3 +171,4 @@ int main()
 
 
 
+
index 392a479..e10758f 100644 (file)
@@ -27,6 +27,7 @@
 #include <stdexcept>
 #include <condition_variable>
 #include <mutex>
+#include <atomic>
 #include "OCPlatform.h"
 #include "OCApi.h"
 
@@ -37,19 +38,18 @@ namespace PH = std::placeholders;
 const uint16_t API_VERSION = 2048;
 const uint16_t TOKEN = 3000;
 
-static OCConnectivityType connectivityType = OC_WIFI;
-
 class ClientFridge
 {
     public:
-    ClientFridge()
+    ClientFridge(OCConnectivityType ct): m_callbackCount(0),
+        m_callsMade(0),m_connectivityType(ct)
     {
-        ostringstream requestURI;
+        std::ostringstream requestURI;
         requestURI << OC_WELL_KNOWN_QUERY << "?rt=intel.fridge";
         std::cout << "Fridge Client has started " <<std::endl;
         FindCallback f (std::bind(&ClientFridge::foundDevice, this, PH::_1));
         OCStackResult result = OCPlatform::findResource(
-                "", requestURI.str(), connectivityType, f);
+                "", requestURI.str(), m_connectivityType, f);
 
         if(OC_STACK_OK != result)
         {
@@ -62,7 +62,7 @@ class ClientFridge
             // its duties, so we block on the CV until we have completed
             // what we are looking to do
             std::unique_lock<std::mutex> lk(m_mutex);
-            m_cv.wait(lk);
+            m_cv.wait(lk, [this]{ return m_callbackCount!=0 && m_callbackCount == m_callsMade;});
         }
     }
 
@@ -83,7 +83,7 @@ class ClientFridge
         std::vector<std::string> lightTypes = {"intel.fridge.light"};
         std::vector<std::string> ifaces = {DEFAULT_INTERFACE};
         OCResource::Ptr light = constructResourceObject(resource->host(),
-                                "/light", connectivityType, false, lightTypes, ifaces);
+                                "/light", m_connectivityType, false, lightTypes, ifaces);
 
         if(!light)
         {
@@ -93,7 +93,7 @@ class ClientFridge
 
         std::vector<std::string> doorTypes = {"intel.fridge.door"};
         OCResource::Ptr leftdoor = constructResourceObject(resource->host(),
-                                "/door/left", connectivityType, false, doorTypes, ifaces);
+                                "/door/left", m_connectivityType, false, doorTypes, ifaces);
 
         if(!leftdoor)
         {
@@ -102,7 +102,7 @@ class ClientFridge
         }
 
         OCResource::Ptr rightdoor = constructResourceObject(resource->host(),
-                                "/door/right", connectivityType, false, doorTypes, ifaces);
+                                "/door/right", m_connectivityType, false, doorTypes, ifaces);
 
         if(!rightdoor)
         {
@@ -111,7 +111,7 @@ class ClientFridge
         }
 
         OCResource::Ptr randomdoor = constructResourceObject(resource->host(),
-                                "/door/random", connectivityType, false, doorTypes, ifaces);
+                                "/door/random", m_connectivityType, false, doorTypes, ifaces);
         if(!randomdoor)
         {
             std::cout << "Error: Random Door Resource Object construction returned null\n";
@@ -139,26 +139,32 @@ class ClientFridge
         // Below, header options are set only for device resource
         resource->setHeaderOptions(headerOptions);
 
+        ++m_callsMade;
         resource->get(QueryParamsMap(), GetCallback(
                 std::bind(&ClientFridge::getResponse, this, "Device", PH::_1,
                     PH::_2, PH::_3, resource, 0)
                 ));
+        ++m_callsMade;
         light->get(QueryParamsMap(), GetCallback(
                 std::bind(&ClientFridge::getResponse, this, "Fridge Light", PH::_1,
                     PH::_2, PH::_3, light, 1)
                 ));
+        ++m_callsMade;
         leftdoor->get(QueryParamsMap(), GetCallback(
                 std::bind(&ClientFridge::getResponse, this, "Left Door", PH::_1,
                     PH::_2, PH::_3, leftdoor, 2)
                 ));
+        ++m_callsMade;
         rightdoor->get(QueryParamsMap(), GetCallback(
                 std::bind(&ClientFridge::getResponse, this, "Right Door", PH::_1,
                     PH::_2, PH::_3, rightdoor, 3)
                 ));
+        ++m_callsMade;
         randomdoor->get(QueryParamsMap(), GetCallback(
                 std::bind(&ClientFridge::getResponse, this, "Random Door", PH::_1,
                     PH::_2, PH::_3, randomdoor, 4)
                 ));
+        ++m_callsMade;
         resource->deleteResource(DeleteCallback(
                 std::bind(&ClientFridge::deleteResponse, this, "Device", PH::_1,
                     PH::_2, resource, 0)
@@ -215,6 +221,12 @@ class ClientFridge
                     break;
                 }
         }
+        ++m_callbackCount;
+
+        if(m_callbackCount == m_callsMade)
+        {
+            m_cv.notify_all();
+        }
     }
 
     //Callback function to handle response for deleteResource call.
@@ -224,6 +236,13 @@ class ClientFridge
         std::cout << "Got a response from delete from the "<< resourceName << std::endl;
         std::cout << "Delete ID is "<<deleteId<<" and resource URI is "<<resource->uri()<<std::endl;
         printHeaderOptions(headerOptions);
+
+        ++m_callbackCount;
+
+        if(m_callbackCount == m_callsMade)
+        {
+            m_cv.notify_all();
+        }
     }
 
     //Function to print the headerOptions received from the server
@@ -241,17 +260,20 @@ class ClientFridge
 
     std::mutex m_mutex;
     std::condition_variable m_cv;
+    std::atomic<int> m_callbackCount;
+    std::atomic<int> m_callsMade;
+    OCConnectivityType m_connectivityType;
 };
 
 int main(int argc, char* argv[])
 {
-
+    OCConnectivityType connectivityType = OC_WIFI;
     if(argc == 2)
     {
         try
         {
             std::size_t inputValLen;
-            int optionSelected = stoi(argv[1], &inputValLen);
+            int optionSelected = std::stoi(argv[1], &inputValLen);
 
             if(inputValLen == strlen(argv[1]))
             {
@@ -274,7 +296,7 @@ int main(int argc, char* argv[])
                 std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
             }
         }
-        catch(exception& e)
+        catch(std::exception& e)
         {
             std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
         }
@@ -297,6 +319,7 @@ int main(int argc, char* argv[])
     };
 
     OCPlatform::Configure(cfg);
-    ClientFridge cf;
+    ClientFridge cf(connectivityType);
     return 0;
 }
+
index 9f90de2..45f626b 100644 (file)
@@ -479,3 +479,4 @@ int main ()
     std::this_thread::sleep_for(std::chrono::minutes(30));
     return 0;
 }
+
index a03c742..ca227e0 100644 (file)
@@ -32,6 +32,7 @@ using namespace OC;
 
 const int SUCCESS_RESPONSE = 0;
 std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
 
 class Garage
 {
@@ -225,9 +226,11 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
 // Callback to found resources
 void foundResource(std::shared_ptr<OCResource> resource)
 {
+    std::lock_guard<std::mutex> lock(resourceLock);
     if(curResource)
     {
         std::cout << "Found another resource, ignoring"<<std::endl;
+        return;
     }
 
     std::string resourceURI;
@@ -283,7 +286,7 @@ void foundResource(std::shared_ptr<OCResource> resource)
 
 int main(int argc, char* argv[]) {
 
-ostringstream requestURI;
+    std::ostringstream requestURI;
 
     OCConnectivityType connectivityType = OC_WIFI;
 
@@ -292,7 +295,7 @@ ostringstream requestURI;
         try
         {
             std::size_t inputValLen;
-            int optionSelected = stoi(argv[1], &inputValLen);
+            int optionSelected = std::stoi(argv[1], &inputValLen);
 
             if(inputValLen == strlen(argv[1]))
             {
@@ -315,7 +318,7 @@ ostringstream requestURI;
                 std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
             }
         }
-        catch(exception& e)
+        catch(std::exception& e)
         {
             std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
         }
@@ -365,3 +368,4 @@ ostringstream requestURI;
     return 0;
 }
 
+
index 1b2dfde..ce6cdfe 100644 (file)
@@ -37,8 +37,7 @@ using namespace std;
 // Forward declaring the entityHandler
 OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request);
 
-/// This class represents a single resource named 'lightResource'. This resource has
-
+/// This class represents a single resource named 'GarageResource'.
 class GarageResource
 {
 public:
@@ -276,7 +275,7 @@ int main(int argc, char* argv[1])
     }
     catch(OCException e)
     {
-        //log(e.what());
+        oclog() << e.what();
     }
 
     // No explicit call to stop the OCPlatform
@@ -284,3 +283,4 @@ int main(int argc, char* argv[1])
 
     return 0;
 }
+
index 88a92db..033a129 100644 (file)
@@ -288,3 +288,4 @@ int main(int argc, char* argv[])
     }
     return 0;
 }
+
index 27caa9c..9c46d10 100644 (file)
@@ -67,9 +67,6 @@ void foundResource(std::shared_ptr< OCResource > resource)
                     cout << "\tresource Error!" << endl;
                 }
             }
-
-            // p_platform.bindResource(resourceHandle, foundResourceHandle);
-
         }
     }
     catch (std::exception& e)
@@ -181,8 +178,9 @@ int main(int argc, char* argv[])
     }
     catch (OCException& e)
     {
-
+        oclog() << "Exception in main: "<< e.what();
     }
 
     return 0;
 }
+
index f95722d..4d08548 100644 (file)
@@ -52,7 +52,7 @@ bool isSlowResponse = false;
 // Forward declaring the entityHandler
 
 /// This class represents a single resource named 'lightResource'. This resource has
-/// two simple properties named 'state' and 'power'
+/// one simple attribute, power
 
 class LightResource
 {
@@ -322,9 +322,9 @@ int main(int argc, char* argv[])
         std::unique_lock<std::mutex> lock(blocker);
         cv.wait(lock);
     }
-    catch(OCException e)
+    catch(OCException& e)
     {
-        //log(e.what());
+       oclog() << "Exception in main: "<< e.what();
     }
 
     // No explicit call to stop the platform.
@@ -332,3 +332,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index c222bc2..446c66e 100644 (file)
@@ -125,3 +125,4 @@ clean:
 clean_apps:
        rm -rf debug
        rm -rf release
+
index 0a646dc..eba8340 100644 (file)
@@ -32,6 +32,7 @@
 using namespace OC;
 
 std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
 
 static int TEST_CASE = 0;
 
@@ -52,7 +53,7 @@ typedef enum {
 
 void printUsage()
 {
-    std::cout << "Usage : presenceclient -t <1|2> -c <0|1>" << std::endl;
+    std::cout << "Usage : presenceclient -t <1|2|3|4|5|6> -c <0|1>" << std::endl;
     std::cout << "-t 1 : Discover Resources and Initiate Unicast Presence" << std::endl;
     std::cout << "-t 2 : Discover Resources and Initiate Unicast Presence with Filter"
               << std::endl;
@@ -97,9 +98,11 @@ void presenceHandler(OCStackResult result, const unsigned int nonce, const std::
 // Callback to found resources
 void foundResource(std::shared_ptr<OCResource> resource)
 {
+    std::lock_guard<std::mutex> lock(resourceLock);
     if(curResource)
     {
         std::cout << "Found another resource, ignoring"<<std::endl;
+        return;
     }
 
     std::string resourceURI;
@@ -198,7 +201,7 @@ void foundResource(std::shared_ptr<OCResource> resource)
 
 int main(int argc, char* argv[]) {
 
-    ostringstream requestURI;
+    std::ostringstream requestURI;
 
     int opt;
 
@@ -211,11 +214,11 @@ int main(int argc, char* argv[]) {
             switch(opt)
             {
                 case 't':
-                    TEST_CASE = stoi(optarg);
+                    TEST_CASE = std::stoi(optarg);
                     break;
                 case 'c':
                     std::size_t inputValLen;
-                    optionSelected = stoi(optarg, &inputValLen);
+                    optionSelected = std::stoi(optarg, &inputValLen);
 
                     if(inputValLen == strlen(optarg))
                     {
@@ -245,7 +248,7 @@ int main(int argc, char* argv[]) {
             }
         }
     }
-    catch(exception& e)
+    catch(std::exception& e)
     {
         std::cout << "Invalid input argument. Using WIFI as connectivity type"
             << std::endl;
@@ -355,11 +358,13 @@ int main(int argc, char* argv[]) {
         std::unique_lock<std::mutex> lock(blocker);
         cv.wait(lock);
 
-    }catch(OCException& e)
+    }
+    catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<< e.what();
     }
 
     return 0;
 }
 
+
index 18e0d7e..ffa84fa 100644 (file)
@@ -245,9 +245,9 @@ int main()
         std::unique_lock<std::mutex> lock(blocker);
         cv.wait(lock);
     }
-    catch(OCException e)
+    catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<< e.what();
     }
 
     // No explicit call to stop the platform.
@@ -255,3 +255,4 @@ int main()
 
     return 0;
 }
+
index cf84a60..c7de0a8 100644 (file)
@@ -33,6 +33,7 @@ using namespace OC;
 
 const int SUCCESS_RESPONSE = 0;
 std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
 
 int observe_count()
 {
@@ -161,6 +162,7 @@ void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, cons
 // Callback to found resources
 void foundResource(std::shared_ptr<OCResource> resource)
 {
+    std::lock_guard<std::mutex> lock(resourceLock);
     if(curResource)
     {
         std::cout << "Found another resource, ignoring"<<std::endl;
@@ -219,7 +221,7 @@ void foundResource(std::shared_ptr<OCResource> resource)
 
 int main(int argc, char* argv[]) {
 
-    ostringstream requestURI;
+    std::ostringstream requestURI;
 
     OCConnectivityType connectivityType = OC_WIFI;
     if(argc == 2)
@@ -227,7 +229,7 @@ int main(int argc, char* argv[]) {
         try
         {
             std::size_t inputValLen;
-            int optionSelected = stoi(argv[1], &inputValLen);
+            int optionSelected = std::stoi(argv[1], &inputValLen);
 
             if(inputValLen == strlen(argv[1]))
             {
@@ -250,7 +252,7 @@ int main(int argc, char* argv[]) {
                 std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
             }
         }
-        catch(exception& e)
+        catch(std::exception& e)
         {
             std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
         }
@@ -293,9 +295,10 @@ int main(int argc, char* argv[]) {
 
     }catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<< e.what();
     }
 
     return 0;
 }
 
+
index 47bbaa0..e81f9af 100644 (file)
@@ -603,3 +603,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index bc6e996..4e3f820 100644 (file)
@@ -68,7 +68,7 @@ void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
         if(eCode == OC_STACK_OK)
         {
             std::cout << "OBSERVE RESULT:"<<std::endl;
-            std::cout << "\tSequenceNumber: "<< sequenceNumber << endl;
+            std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
             rep.getValue("state", mylight.m_state);
             rep.getValue("power", mylight.m_power);
             rep.getValue("name", mylight.m_name);
@@ -126,9 +126,9 @@ void onPost2(const HeaderOptions& headerOptions, const OCRepresentation& rep, co
             }
 
             if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
-                std::cout << endl << "Observe is used." << endl << endl;
+                std::cout << std::endl << "Observe is used." << std::endl << std::endl;
             else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
-                std::cout << endl << "ObserveAll is used." << endl << endl;
+                std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
 
             curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
 
@@ -313,7 +313,7 @@ void getLightRepresentation(std::shared_ptr<OCResource> resource)
 // Callback to found resources
 void foundResource(std::shared_ptr<OCResource> resource)
 {
-    cout << "In foundResource\n";
+    std::cout << "In foundResource\n";
     std::string resourceURI;
     std::string hostAddress;
     try
@@ -437,7 +437,7 @@ void checkConnectivityValue(int value)
 
 int main(int argc, char* argv[]) {
 
-    ostringstream requestURI;
+    std::ostringstream requestURI;
 
     try
     {
@@ -449,14 +449,14 @@ int main(int argc, char* argv[]) {
         else if (argc == 2)
         {
 
-            checkObserverValue(stoi(argv[1]));
+            checkObserverValue(std::stoi(argv[1]));
             std::cout << "<===No ConnectivtyType selected. "
                       << "Setting ConnectivityType to WIFI===>\n\n";
         }
         else if(argc == 3)
         {
-            checkObserverValue(stoi(argv[1]));
-            checkConnectivityValue(stoi(argv[2]));
+            checkObserverValue(std::stoi(argv[1]));
+            checkConnectivityValue(std::stoi(argv[2]));
         }
         else
         {
@@ -464,7 +464,7 @@ int main(int argc, char* argv[]) {
             return -1;
         }
     }
-    catch(exception& e)
+    catch(std::exception& e)
     {
         std::cout << "<===Invalid input arguments===>\n\n";
         return -1;
@@ -509,9 +509,10 @@ int main(int argc, char* argv[]) {
 
     }catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<<e.what();
     }
 
     return 0;
 }
 
+
index 12a5ee9..ea3588f 100644 (file)
@@ -43,6 +43,7 @@ typedef std::set<std::shared_ptr<OCResource>, dereference_compare> DiscoveredRes
 DiscoveredResourceSet discoveredResources;
 const int SUCCESS_RESPONSE = 0;
 std::shared_ptr<OCResource> curResource;
+std::mutex resourceLock;
 static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
 
 //TODO-CA: Since CA CON message support is still in progress, this client uses
@@ -77,18 +78,18 @@ void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep,
         std::cout << "OBSERVE RESULT:"<<std::endl;
         if(sequenceNumber == (int) ObserveAction::ObserveRegister)
         {
-            std::cout << "\tObserve Registration Confirmed: "<< endl;
+            std::cout << "\tObserve Registration Confirmed: "<< std::endl;
         }
         else if (sequenceNumber == (int) ObserveAction::ObserveUnregister)
         {
-            std::cout << "\tObserve Cancel Confirmed: "<< endl;
+            std::cout << "\tObserve Cancel Confirmed: "<< std::endl;
             sleep(10);
             std::cout << "DONE"<<std::endl;
             std::exit(0);
         }
         else
         {
-            std::cout << "\tSequenceNumber: "<< sequenceNumber << endl;
+            std::cout << "\tSequenceNumber: "<< sequenceNumber << std::endl;
         }
 
         rep.getValue("state", mylight.m_state);
@@ -137,9 +138,9 @@ void onPost2(const HeaderOptions& headerOptions, const OCRepresentation& rep, co
         }
 
         if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
-            std::cout << endl << "Observe is used." << endl << endl;
+            std::cout << std::endl << "Observe is used." << std::endl << std::endl;
         else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
-            std::cout << endl << "ObserveAll is used." << endl << endl;
+            std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
         sleep(1);
         curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve,
                 OC::QualityOfService::LowQos);
@@ -302,26 +303,28 @@ void foundResource(std::shared_ptr<OCResource> resource)
     std::string hostAddress;
     try
     {
-        if(discoveredResources.find(resource) == discoveredResources.end())
-        {
-            std::cout << "Found resource " << resource->uniqueIdentifier() <<
-                " for the first time on server with ID: "<< resource->sid()<<std::endl;
-            discoveredResources.insert(resource);
-        }
-        else
-        {
-            std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
-        }
-
-        if(curResource)
-        {
-            std::cout << "Found another resource, ignoring"<<std::endl;
-            return;
-        }
-
         // Do some operations with resource object.
         if(resource)
         {
+            std::lock_guard<std::mutex> lk(resourceLock);
+
+            if(discoveredResources.find(resource) == discoveredResources.end())
+            {
+                std::cout << "Found resource " << resource->uniqueIdentifier() <<
+                    " for the first time on server with ID: "<< resource->sid()<<std::endl;
+                discoveredResources.insert(resource);
+            }
+            else
+            {
+                std::cout<<"Found resource "<< resource->uniqueIdentifier() << " again!"<<std::endl;
+            }
+
+            if(curResource)
+            {
+                std::cout << "Found another resource, ignoring"<<std::endl;
+                return;
+            }
+
             std::cout<<"DISCOVERED Resource:"<<std::endl;
             // Get the resource URI
             resourceURI = resource->uri();
@@ -349,7 +352,8 @@ void foundResource(std::shared_ptr<OCResource> resource)
             {
                 curResource = resource;
                 sleep(1);
-                // Call a local function which will internally invoke get API on the resource pointer
+                // Call a local function which will internally invoke get
+                // API on the resource pointer
                 getLightRepresentation(resource);
             }
         }
@@ -379,7 +383,7 @@ void PrintUsage()
 
 int main(int argc, char* argv[]) {
 
-    ostringstream requestURI;
+    std::ostringstream requestURI;
 
     OCConnectivityType connectivityType = OC_WIFI;
     try
@@ -388,9 +392,9 @@ int main(int argc, char* argv[]) {
         {
             OBSERVE_TYPE_TO_USE = ObserveType::Observe;
         }
-        else if (argc >= 2)
+        else if (argc ==2 || argc==3)
         {
-            int value = stoi(argv[1]);
+            int value = std::stoi(argv[1]);
             if (value == 1)
                 OBSERVE_TYPE_TO_USE = ObserveType::Observe;
             else if (value == 2)
@@ -401,7 +405,7 @@ int main(int argc, char* argv[]) {
             if(argc == 3)
             {
                 std::size_t inputValLen;
-                int optionSelected = stoi(argv[2], &inputValLen);
+                int optionSelected = std::stoi(argv[2], &inputValLen);
 
                 if(inputValLen == strlen(argv[2]))
                 {
@@ -432,7 +436,7 @@ int main(int argc, char* argv[]) {
             return -1;
         }
     }
-    catch(exception& e)
+    catch(std::exception& e)
     {
         std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
     }
@@ -474,11 +478,13 @@ int main(int argc, char* argv[]) {
         std::unique_lock<std::mutex> lock(blocker);
         cv.wait(lock);
 
-    }catch(OCException& e)
+    }
+    catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<<e.what();
     }
 
     return 0;
 }
 
+
index 04a9cb1..6a5a947 100644 (file)
 #include "OCApi.h"
 using namespace OC;
 
-OCConnectivityType connectivityType = OC_WIFI;
 
 class ClientWorker
 {
 private:
-    bool m_isFoo;
-    int m_barCount;
     void putResourceInfo(const HeaderOptions& headerOptions,
             const OCRepresentation rep, const OCRepresentation rep2, const int eCode)
     {
@@ -144,15 +141,18 @@ private:
     }
 
 public:
+    ClientWorker(OCConnectivityType ct):m_connectivityType{ct}
+    {}
+
     void start()
     {
-        ostringstream requestURI;
+        std::ostringstream requestURI;
         requestURI << OC_WELL_KNOWN_QUERY << "?rt=core.foo";
 
         std::cout<<"Starting Client find:"<<std::endl;
         FindCallback f (std::bind(&ClientWorker::foundResource, this, std::placeholders::_1));
         std::cout<<"result:" <<
-        OCPlatform::findResource("", requestURI.str(), connectivityType, f)
+        OCPlatform::findResource("", requestURI.str(), m_connectivityType, f)
         << std::endl;
 
         std::cout<<"Finding Resource..."<<std::endl;
@@ -167,6 +167,9 @@ private:
     std::mutex m_resourceLock;
     std::condition_variable m_cv;
     std::shared_ptr<OCResource> m_resource;
+    OCConnectivityType m_connectivityType;
+    bool m_isFoo;
+    int m_barCount;
 };
 
 struct FooResource
@@ -297,13 +300,14 @@ struct FooResource
 
 int main(int argc, char* argv[])
 {
+    OCConnectivityType connectivityType = OC_WIFI;
 
     if(argc == 2)
     {
         try
         {
             std::size_t inputValLen;
-            int optionSelected = stoi(argv[1], &inputValLen);
+            int optionSelected = std::stoi(argv[1], &inputValLen);
 
             if(inputValLen == strlen(argv[1]))
             {
@@ -326,7 +330,7 @@ int main(int argc, char* argv[])
                 std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
             }
         }
-        catch(exception& e)
+        catch(std::exception& e)
         {
             std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
         }
@@ -358,7 +362,7 @@ int main(int argc, char* argv[])
             return -1;
         }
 
-        ClientWorker cw;
+        ClientWorker cw(connectivityType);
         cw.start();
     }
     catch(OCException& e)
@@ -368,3 +372,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index e395909..e6552ed 100644 (file)
@@ -536,7 +536,7 @@ int main(int argc, char* argv[])
         std::mutex blocker;
         std::condition_variable cv;
         std::unique_lock<std::mutex> lock(blocker);
-        cv.wait(lock);
+        cv.wait(lock, []{return false;});
     }
     catch(OCException &e)
     {
@@ -548,3 +548,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index cf0d09a..7307ebb 100644 (file)
@@ -79,7 +79,8 @@ public:
     void createResource()
     {
         std::string resourceURI = m_lightUri; // URI of the resource
-        std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
+        // resource type name. In this case, it is light
+        std::string resourceTypeName = "core.light";
         std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
 
         // OCResourceProperty is defined ocstack.h
@@ -410,7 +411,7 @@ void * ChangeLightRepresentation (void *param)
 void PrintUsage()
 {
     std::cout << std::endl;
-    std::cout << "Usage : simplserver <isListOfObservers>\n";
+    std::cout << "Usage : simpleserver <isListOfObservers>\n";
     std::cout << "   ObserveType : 0 - Observe All\n";
     std::cout << "   ObserveType : 1 - Observe List of observers\n\n";
 }
@@ -450,7 +451,8 @@ int main(int argc, char* argv[])
 
     try
     {
-        // Create the instance of the resource class (in this case instance of class 'LightResource').
+        // Create the instance of the resource class
+        // (in this case instance of class 'LightResource').
         LightResource myLight(cfg);
 
         // Invoke createResource function of class light.
@@ -466,11 +468,11 @@ int main(int argc, char* argv[])
         std::mutex blocker;
         std::condition_variable cv;
         std::unique_lock<std::mutex> lock(blocker);
-        cv.wait(lock);
+        cv.wait(lock, []{return false;});
     }
-    catch(OCException e)
+    catch(OCException& e)
     {
-        //log(e.what());
+        oclog() << "Exception in main: "<< e.what();
     }
 
     // No explicit call to stop the platform.
@@ -478,3 +480,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index 8a365e2..b421f60 100644 (file)
@@ -340,7 +340,7 @@ int main(int argc, char* argv[])
         try
         {
             std::size_t inputValLen;
-            int optionSelected = stoi(argv[1], &inputValLen);
+            int optionSelected = std::stoi(argv[1], &inputValLen);
 
             if(inputValLen == strlen(argv[1]))
             {
@@ -363,7 +363,7 @@ int main(int argc, char* argv[])
                 std::cout << "Invalid connectivity type selected. Using default WIFI" << std::endl;
             }
         }
-        catch(exception& e)
+        catch(std::exception& e)
         {
             std::cout << "Invalid input argument. Using WIFI as connectivity type" << std::endl;
         }
@@ -427,3 +427,4 @@ int main(int argc, char* argv[])
 
     return 0;
 }
+
index 448b970..4d17d9d 100644 (file)
@@ -453,3 +453,4 @@ namespace OC
 #endif //__OCPLATFORM_H
 
 
+
index 20a83ae..9064830 100644 (file)
 
 namespace OC
 {
-    /**
-    *   @brief Both server and client must initialize the core platform by instantiating OCPlatform.
-    *          On successful initialization, an instance of the OCPlatform is returned.
-    *          APIs in OCPlatform provide mechanism to register a resource and host the resource
-    *          on the server, find resources on the network etc.
-    */
     class OCPlatform_impl
     {
     private:
         static PlatformConfig& globalConfig();
     public:
-        /**
-         * API for overwriting the default configuration of the OCPlatform object.
-         * Note: Any calls made to this AFTER the first call to OCPlatform::Instance
-         * will have no affect
-         */
         static void Configure(const PlatformConfig& config);
 
-        /**
-         * API for retrieving the current OCPlatform object.  This will use the
-         * default platform config, unless the default is over-written using the
-         * Configure method before the first call to instance.
-         */
         static OCPlatform_impl& Instance();
 
     public:
         // typedef for handle to cancel presence info with
         typedef OCDoHandle OCPresenceHandle;
 
-        /**
-        * Virtual destructor
-        */
         virtual ~OCPlatform_impl(void);
 
-        /**
-        * API for notifying base that resource's attributes have changed.
-        *
-        * @param OCResourceHandle resource handle of the resource
-        * @param QualityOfService the quality of communication
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-        * NOTE: This API is for server side only.
-        * NOTE: OCResourceHandle is defined in ocstack.h.
-        * NOTE: OCStackResult is defined in ocstack.h.
-        */
         OCStackResult notifyAllObservers(OCResourceHandle resourceHandle);
+
         OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS);
 
-        /**
-        * API for notifying only specific clients that resource's attributes have changed.
-        *
-        * @param OCResourceHandle resource handle of the resource
-        * @param observationIds std vector of observationIds. These set of ids are ones which
-        * which will be notified upon resource change.
-        * @param responsePtr OCResourceResponse pointer used by app to fill the response for this
-        * resource change.
-        * @param QualityOfService the quality of communication
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-        *
-        * NOTE: This API is for server side only.
-        * NOTE: OCResourceHandle is defined in ocstack.h.
-        * NOTE: OCStackResult is defined in ocstack.h.
-        */
         OCStackResult notifyListOfObservers(
                     OCResourceHandle resourceHandle,
                     ObservationIds& observationIds,
                     const std::shared_ptr<OCResourceResponse> responsePtr);
+
         OCStackResult notifyListOfObservers(
                     OCResourceHandle resourceHandle,
                     ObservationIds& observationIds,
                     const std::shared_ptr<OCResourceResponse> responsePtr,
                     QualityOfService QoS);
 
-        /**
-        * API for Service and Resource Discovery.
-        * NOTE: This API applies to client side only.
-        *
-        * @param host - Host IP Address of a service to direct resource discovery query. If null or
-        *        empty, performs multicast resource discovery query
-        * @param resourceURI - name of the resource. If null or empty, performs search for all
-        *        resource names
-        * @param handler - Handles callbacks, success states and failure states.
-        *
-        *        Four modes of discovery defined as follows:
-        *        (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource
-        *                                   discovery.
-        *        (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular
-        *                                   resource(s) from ALL services.
-        *        (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service.
-        *        (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular
-        *                                   resource(s) from a particular service.
-        * @param QualityOfService the quality of communication
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-        * NOTE: First parameter 'host' currently represents an IP address. This will change in
-        * future and will refer to endpoint interface so that we can refer to other transports such
-        * as BTH etc.
-        * NOTE: OCStackResult is defined in ocstack.h.
-        */
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
                     OCConnectivityType connectivityType, FindCallback resourceHandler);
+
         OCStackResult findResource(const std::string& host, const std::string& resourceURI,
                     OCConnectivityType connectivityType, FindCallback resourceHandler,
                     QualityOfService QoS);
-        /**
-         * API for Device Discovery
-         *
-         * @param host - Host IP Address. If null or empty, Multicast is performed.
-         * @param resourceURI - Uri containing address to the virtual device in C Stack
-         *                       ("/oc/core/d")
-         *
-         * @param QualityOfService the quality of communication
-         *
-         */
+
         OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
                     OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler);
+
         OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI,
                     OCConnectivityType connectivityType, FindDeviceCallback deviceInfoHandler,
                     QualityOfService QoS);
@@ -197,268 +120,49 @@ namespace OC
                         EntityHandler entityHandler,
                         uint8_t resourceProperty);
 
-        /**
-         * This API registers a resource with the server
-         * NOTE: This API applies to server & client side.
-
-         * @param resourceHandle - Upon successful registration, resourceHandle will be filled
-         * @param OCResource - The instance of OCResource that all data filled.
-         *
-         * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-         */
-
         OCStackResult registerResource(OCResourceHandle& resourceHandle,
                         const std::shared_ptr<OCResource> resource);
 
-        /**
-         * This API registers all the device specific information
-         *
-         * @param OCDeviceInfo - Structure containing all the device related information
-         *
-         * @return OCStackResult return value of the API. Returns OC_STACK_OK if success
-         *
-         * Note: OCDeviceInfo is defined in OCStack.h
-         */
         OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo);
 
-        /**
-        * Set default device entity handler
-        *
-        * @param entityHandler - entity handler to handle requests for
-        *                        any undefined resources or default actions.
-        *                        if NULL is passed it removes the device default entity handler.
-        *
-        * @return
-        *     OC_STACK_OK    - no errors
-        *     OC_STACK_ERROR - stack process error
-        */
         OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler);
 
-        /**
-        * This API unregisters a resource with the server
-        * NOTE: This API applies to server side only.
-        *
-        * @param resourceHandle - This is the resource handle which we which to unregister from the
-        *                           server
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
-        * NOTE: OCStackResult is defined in ocstack.h.
-        */
         OCStackResult unregisterResource(const OCResourceHandle& resourceHandle) const;
 
-        /**
-        * Add a resource to a collection resource.
-        *
-        * @param collectionHandle - handle to the collection resource
-        * @param addedResourceHandle - handle to resource to be added to the collection resource
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.<br>
-        * NOTE: OCStackResult is defined in ocstack.h. <br>
-        * NOTE: bindResource must be used only after the both collection resource and
-        * resource to add under a collections are created and respective handles obtained<br>
-        * <b>Example:</b> <br>
-        * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
-        *               entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
-        *               entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);<br>
-        * At the end of Step 3, resource "a/home" will contain a reference to "a/kitchen".<br>
-        */
         OCStackResult bindResource(const OCResourceHandle collectionHandle,
                     const OCResourceHandle resourceHandle);
 
-        /**
-        * Add multiple resources to a collection resource.
-        *
-        * @param collectionHandle - handle to the collection resource
-        * @param addedResourceHandleList reference to list of resource handles to be added to
-        *       the collection resource
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
-        * NOTE: OCStackResult is defined in ocstack.h. <br>
-        * NOTE: bindResources must be used only after the both collection resource and
-        * list of resources to add under a collection are created and respective handles
-        * obtained<br>
-        * <b> Example: </b> <br>
-        * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
-        *           homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
-        *           kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface,
-        *           roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 4: std::vector<OCResourceHandle> rList; rList.push_back(kitchenResourceHandle);
-        *           rList.push_back(roomResourceHandle);<br>
-        * Step 5: bindResource(homeResourceHandle, rList);<br>
-        * At the end of Step 5, resource "a/home" will contain a references to "a/kitchen"
-        *           and "a/room" <br>
-        */
         OCStackResult bindResources(const OCResourceHandle collectionHandle,
                     const std::vector<OCResourceHandle>& addedResourceHandleList);
 
-        /**
-        * Unbind a resource from a collection resource.
-        *
-        * @param collectionHandle - handle to the collection resource
-        * @param resourceHandle resource handle to be unbound from the collection resource
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
-        * NOTE: OCStackResult is defined in ocstack.h.<br>
-        * NOTE: unbindResource must be used only after the both collection resource and
-        * resource to unbind from a collection are created and respective handles obtained<br>
-        * <b> Example </b> <br>
-        * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
-        *       entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
-        *       entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);<br>
-        * Step 4: unbindResource(homeResourceHandle, kitchenResourceHandle);<br>
-        * At the end of Step 4, resource "a/home" will no longer reference "a/kitchen". <br>
-        */
         OCStackResult unbindResource(const OCResourceHandle collectionHandle,
                     const OCResourceHandle resourceHandle);
 
-        /**
-        * Unbind resources from a collection resource.
-        *
-        * @param collectionHandle - handle to the collection resource
-        * @param resourceHandleList List of resource handles to be unbound from the collection
-        *   resource
-        *
-        * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. <br>
-        *
-        * NOTE: OCStackResult is defined in ocstack.h.<br>
-        * NOTE: unbindResources must be used only after the both collection resource and
-        * list of resources resource to unbind from a collection are created and respective handles
-        * obtained. <br>
-        * <b>Example</b> <br>
-        * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface,
-        *       homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface,
-        *       kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface,
-        *       roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);<br>
-        * Step 4: std::vector<OCResourceHandle> rList; rList.push_back(kitchenResourceHandle);
-        *       rList.push_back(roomResourceHandle);<br>
-        * Step 5: bindResource(homeResourceHandle, rList);<br>
-        * Step 6: unbindResources(homeResourceHandle, rList);<br>
-        * At the end of Step 6, resource "a/home" will no longer reference to "a/kitchen"
-        *       and "a/room"<br>
-        */
         OCStackResult unbindResources(const OCResourceHandle collectionHandle,
                         const std::vector<OCResourceHandle>& resourceHandleList);
 
-        /**
-        * Binds a type to a particular resource
-        * @param resourceHandle - handle to the resource
-        * @param resourceTypeName - new typename to bind to the resource
-
-        * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
-        */
         OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle,
                         const std::string& resourceTypeName) const;
 
-        /**
-        * Binds an interface to a particular resource
-        * @param resourceHandle - handle to the resource
-        * @param resourceTypeName - new interface  to bind to the resource
-
-        * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
-        */
         OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle,
                         const std::string& resourceInterfaceName) const;
 
-        /**
-        * Start Presence announcements.
-        *
-        * @param ttl - time to live
-        * @return OCStackResult - Returns OCSTACK_OK if success <br>
-        *
-        * Server can call this function when it comes online for the
-        * first time, or when it comes back online from offline mode,
-        * or when it re enters network.
-        *
-        */
         OCStackResult startPresence(const unsigned int ttl);
 
-        /**
-        * Stop Presence announcements.
-        *
-        * @return OCStackResult - Returns OCSTACK_OK if success <br>
-        *
-        * Server can call this function when it is terminating,
-        * going offline, or when going away from network.
-        *
-        */
         OCStackResult stopPresence();
 
-        /**
-        * subscribes to a server's presence change events.  By making this subscription,
-        * every time a server adds/removes/alters a resource, starts or is intentionally
-        * stopped (potentially more to be added later).
-        *
-        * @param presenceHandle - a handle object that can be used to identify this subscription
-        *               request.  It can be used to unsubscribe from these events in the future.
-        *               It will be set upon successful return of this method.
-        * @param host - The IP address/addressable name of the server to subscribe to.
-        * @param resourceType - a resource type specified as a filter for subscription callbacks.
-        * @param presenceHandler - callback function that will receive notifications/subscription
-        *                           events
-        *
-        * @return OCStackResult - return value of the API.  Returns OCSTACK_OK if success <br>
-        */
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
                         OCConnectivityType connectivityType, SubscribeCallback presenceHandler);
+
         OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host,
                         const std::string& resourceType, OCConnectivityType connectivityType,
                         SubscribeCallback presenceHandler);
-        /**
-        * unsubscribes from a previously subscribed server's presence events. Note that
-        * you may for a short time still receive events from the server since it may take time
-        * for the unsubscribe to take effect.
-        *
-        * @param presenceHandle - the handle object provided by the subscribePresence call that
-        *               identifies this subscription.
-        *
-        * @return OCStackResult - return value of the API.  Returns OCSTACK_OK if success <br>
-        */
         OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle);
 
-        /**
-        * Creates a resource proxy object so that get/put/observe functionality
-        * can be used without discovering the object in advance.  Note that the
-        * consumer of this method needs to provide all of the details required to
-        * correctly contact and observe the object. If the consumer lacks any of
-        * this information, they should discover the resource object normally.
-        * Additionally, you can only create this object if OCPlatform was initialized
-        * to be a Client or Client/Server.  Otherwise, this will return an empty
-        * shared ptr.
-        *
-        * @param host - a string containing a resolvable host address of the server
-        *           holding the resource. Currently this should be in the format
-        *           coap://address:port, though in the future, we expect this to
-        *           change to //address:port
-        *
-        * @param uri - the rest of the resource's URI that will permit messages to be
-        *           properly routed.  Example: /a/light
-        *
-        * @param isObservable - a boolean containing whether the resource supports observation
-        *
-        * @param resourceTypes - a collection of resource types implemented by the resource
-        *
-        * @param interfaces - a collection of interfaces that the resource supports/implements
-        * @return OCResource::Ptr - a shared pointer to the new resource object
-        */
         OCResource::Ptr constructResourceObject(const std::string& host, const std::string& uri,
                         OCConnectivityType connectivityType, bool isObservable,
                         const std::vector<std::string>& resourceTypes,
                         const std::vector<std::string>& interfaces);
-        /**
-        * Allows application entity handler to send response to an incoming request.
-        *
-        * @param pResponse - OCResourceResponse pointer that will permit to set values related
-        * to resource response. <br>
-        * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success <br>
-        */
         OCStackResult sendResponse(const std::shared_ptr<OCResourceResponse> pResponse);
 
     private:
@@ -472,8 +176,8 @@ namespace OC
 
     private:
         /**
-        * Constructor for OCPlatform. Constructs a new OCPlatform from a given PlatformConfig with
-        * appropriate fields
+        * Constructor for OCPlatform_impl. Constructs a new OCPlatform_impl from a given
+        * PlatformConfig with appropriate fields
         * @param config PlatformConfig struct which has details such as modeType
         * (server/client/both), in-proc/out-of-proc etc.
         */
@@ -497,3 +201,4 @@ namespace OC
 #endif //__OCPLATFORM_IMPL_H
 
 
+
index 2082597..bdb18c5 100644 (file)
@@ -77,7 +77,7 @@ namespace OC
         public:
             void setJSONRepresentation(const std::string& payload);
 
-            void setJSONRepresentation(const unsigned char* payload);
+            void setJSONRepresentation(const char* payload);
 
             std::string getJSONRepresentation(OCInfoFormat f) const;
 
@@ -403,3 +403,4 @@ namespace OC
 
 
 #endif //__OCREPRESENTATION_H
+
index 26c9c5d..6d38874 100644 (file)
@@ -42,7 +42,7 @@ namespace OC
 {
     class OCResource;
     class OCResourceIdentifier;
-    ostream& operator <<(ostream& os, const OCResourceIdentifier& ri);
+    std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri);
     /**
     *  @brief  OCResourceIdentifier represents the identity information for a server. This
     *          object combined with the OCResource's URI property uniquely identify an
@@ -53,7 +53,7 @@ namespace OC
     class OCResourceIdentifier
     {
         friend class OCResource;
-        friend ostream& operator <<(ostream& os, const OCResourceIdentifier& ri);
+        friend std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri);
 
         public:
             bool operator==(const OCResourceIdentifier &other) const;
@@ -407,3 +407,4 @@ namespace OC
 } // namespace OC
 
 #endif //__OCRESOURCE_H
+
index 4835235..54ffadb 100644 (file)
@@ -33,8 +33,6 @@
 #include <ocstack.h>
 #include <OCRepresentation.h>
 
-using namespace std;
-
 namespace OC
 {
     class InProcServerWrapper;
@@ -275,3 +273,4 @@ namespace OC
 } // namespace OC
 
 #endif //__OCRESOURCERESPONSE_H
+
index 6f9f541..898fde7 100644 (file)
@@ -202,7 +202,7 @@ namespace OC
             std::string ConvertOCAddrToString(OCSecureType sec, int secureport)
             {
                 uint16_t port;
-                ostringstream os;
+                std::ostringstream os;
 
                 if(sec== OCSecureType::IPv4)
                 {
@@ -288,3 +288,4 @@ namespace OC
             OCConnectivityType m_connectivityType;
     };
 }
+
index cf01b8d..3039275 100644 (file)
@@ -34,18 +34,14 @@ namespace OC {
     namespace Utilities {
 
         typedef std::map<std::string, std::string> QueryParamsKeyVal;
+
         /*
-         * @brief Helper function to get query parameter from a URI
-         * @remarks      Its okay to return a copy of the container.\
-         *               The size is not expected to be huge.
-         * @remarks      Temporary: The URI must strictly have\
-         *               coap as the protocol in the fully qualified URI\
-         *               e.g., coap://1.2.3.4:5657/foo?bar=0)
-         * @remarks      If a separate class for URI parser is needed,\
-         *               please talk to Erich Keane.
-         * @todo         If more URI elements need to be parsed,\
-         *               please move the common parsing logic to a
-         *               different function
+         * @brief helper function that parses the query parameters component
+         * of a URI into a key-value map.  This function expects the uri
+         * parameter to contain the query parameters component of a URI
+         * (everything after the '?', excluding anything anchors).
+         *
+         * Note that output will not perform URL decoding
          */
         QueryParamsKeyVal getQueryParams(const std::string& uri);
 
@@ -117,3 +113,4 @@ namespace OC
 } // namespace OC
 
 #endif
+
index b8b8808..355b6a7 100644 (file)
@@ -23,8 +23,6 @@
 
 #include <string>
 
-using namespace std;
-
 namespace OC
 {
     namespace InitException
@@ -136,3 +134,4 @@ namespace OC
 }
 
 #endif // _STRING_CONSTANTS_H_
+
index fa22f75..505e9a3 100644 (file)
@@ -130,3 +130,4 @@ clean_legacy:
        -rm -f -v $(OBJ_DIR)/liboc.a $(OBJ_DIR)/*.o
        cd csdk && $(MAKE) clean
        cd csdk && $(MAKE) deepclean
+
index 52e665e..99f43b8 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # liboc_logger (share library) build script
 ##
@@ -33,3 +53,4 @@ liboc_logger_env.InstallTarget([liboc_logger_core, liboc_logger], 'liboc_logger'
 
 if target_os not in ['ios']:
        SConscript('examples/SConscript')
+
index bc4b4a8..7b2db2b 100644 (file)
@@ -24,8 +24,8 @@
 #include <stdlib.h>
 
 oc_log_ctx_t *oc_log_make_ctx(
-                                                       void*                             world,
-                            const oc_log_level           level,
+                            void*                 world,
+                            const oc_log_level    level,
                             oc_log_init_t         init,
                             oc_log_destroy_t      destroy,
                             oc_log_flush_t        flush,
@@ -42,15 +42,21 @@ oc_log_ctx_t *oc_log_make_ctx(
     0 == set_level ||
     0 == write_level ||
     0 == set_module)
+ {
   return 0;
+ }
 
  if(OC_LOG_MIN_VAL__ >= level || OC_LOG_MAX_VAL__ <= level)
-  return 0;
+ {
+     return 0;
+ }
 
  log_ctx = (oc_log_ctx_t *)malloc(sizeof(oc_log_ctx_t));
 
- if(0 == log_ctx)
-  return 0;
+ if(!log_ctx)
+ {
+     return 0;
+ }
 
  log_ctx->ctx           = 0; /* we'll get to this in a sec... */
  log_ctx->log_level     = level;
@@ -59,11 +65,11 @@ oc_log_ctx_t *oc_log_make_ctx(
  log_ctx->destroy       = destroy;
  log_ctx->flush         = flush;
  log_ctx->set_level     = set_level;
- log_ctx->set_module   = set_module;
+ log_ctx->set_module    = set_module;
 
  log_ctx->write_level   = write_level;
 
- if(0 == log_ctx->init(log_ctx, world))
+ if(!log_ctx->init(log_ctx, world))
   {
     free(log_ctx);
     return 0;
@@ -74,82 +80,98 @@ oc_log_ctx_t *oc_log_make_ctx(
 
 void oc_log_destroy(oc_log_ctx_t *ctx)
 {
- if(0 == ctx)
-  return;
+ if(!ctx)
+ {
+     return;
+ }
 
  ctx->destroy(ctx);
 
  if(0 != ctx->module_name)
-  free(ctx->module_name);
+ {
+     free(ctx->module_name);
+ }
 
  free(ctx);
 }
 
 int oc_log_init(oc_log_ctx_t *ctx, void *world)
 {
- if(0 == ctx)
-  return 0;
+ if(!ctx)
+ {
+     return 0;
+ }
 
  return ctx->init(ctx, world);
 }
 
 void oc_log_flush(oc_log_ctx_t *ctx)
 {
-    if(0 == ctx)
+    if(!ctx)
     {
         return;
     }
     ctx->flush(ctx);
 }
 
-void oc_log_set_level(oc_log_ctx_t *ctx, const oc_log_level ll)
+void oc_log_set_level(oc_log_ctx_t *ctx, const oc_log_level loglevel)
 {
-    if(0 == ctx)
+    if(!ctx)
     {
         return;
     }
-    ctx->set_level(ctx, ll);
+    ctx->set_level(ctx, loglevel);
 }
 
 size_t oc_log_write(oc_log_ctx_t *ctx, const char *msg)
 {
- if(0 == ctx)
-  return 0;
+    if(!ctx)
+    {
+        return 0;
+    }
 
  return oc_log_write_level(ctx, ctx->log_level, msg);
 }
 
-size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level ll, const char *msg)
+size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level loglevel, const char *msg)
 {
- if(0 == ctx)
-  return 0;
+ if(!ctx)
+ {
+     return 0;
+ }
 
- ctx->log_level = ll;
+ ctx->log_level = loglevel;
 
  /* Notify: */
- return ctx->write_level(ctx, ll, msg);
+ return ctx->write_level(ctx, loglevel, msg);
 }
 
 int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name)
 {
- char *mn;
- size_t l;
+ char *mn = NULL;
+ size_t len = 0;
 
- if(0 == ctx)
-  return 0;
+ if(!ctx || !module_name)
+ {
+     return 0;
+ }
 
  /* Swap pointers so that module data's not erased in the event of failure: */
- l = strlen(module_name);
+ len = strlen(module_name);
 
- mn = (char *)malloc(1 + l);
+ mn = (char *)malloc(1 + len);
 
- if(0 == mn)
-  return 0;
+ if(!mn)
+ {
+     return 0;
+ }
 
- memcpy(mn, module_name, 1 + l);
+ memcpy(mn, module_name, 1 + len);
 
- if(0 != ctx->module_name)
-  free(ctx->module_name);
+ if(!ctx->module_name)
+ {
+     free(ctx->module_name);
+ }
 
  ctx->module_name = mn;
 
@@ -157,3 +179,4 @@ int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name)
  return ctx->set_module(ctx, ctx->module_name);
 }
 
+
index de1ab4a..644ec78 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # liboc_logger examples build script
 ##
@@ -32,3 +52,4 @@ examples_cpp = examples_env.Program('examples_cpp', 'test_logging.cpp')
 
 Alias('liboc_logger_examples', [examples_c, examples_cpp])
 examples_env.AppendTarget('liboc_logger_examples')
+
index bf8f3de..2c807c7 100644 (file)
@@ -27,7 +27,8 @@
  extern "C" {
 #endif
 
- typedef enum {
+ typedef enum
+ {
      OC_LOG_MIN_VAL__   = -1,
      OC_LOG_ALL         = 0,
      OC_LOG_FATAL,
@@ -82,3 +83,4 @@ typedef int    (*oc_log_try_lock_t)      (oc_log_ctx_t *);
 #endif
 
 #endif
+
index bab1646..4bb1df4 100644 (file)
@@ -83,3 +83,4 @@ clean: legacy_clean
 
 legacy_clean:
        rm -f *.o $(PROGRAMS)
+
index 9287106..927eeff 100644 (file)
@@ -33,6 +33,7 @@
 #include <OCResourceResponse.h>
 #include <ocstack.h>
 #include <OCApi.h>
+#include <ocmalloc.h>
 #include <OCPlatform.h>
 #include <OCUtilities.h>
 
@@ -73,9 +74,8 @@ void formResourceRequest(OCEntityHandlerFlag flag,
         {
             if(entityHandlerRequest->query)
             {
-                std::string querystr(reinterpret_cast<char*>(entityHandlerRequest->query));
-
-                OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(querystr);
+                OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(
+                        entityHandlerRequest->query);
 
                 if(qp.size() > 0)
                 {
@@ -582,7 +582,15 @@ namespace OC
             response.requestHandle = pResponse->getRequestHandle();
             response.resourceHandle = pResponse->getResourceHandle();
             response.ehResult = pResponse->getResponseResult();
-            response.payload = (unsigned char*) payLoad.c_str();
+
+            response.payload = static_cast<char*>(OCMalloc(payLoad.length() + 1));
+            if(!response.payload)
+            {
+                result = OC_STACK_NO_MEMORY;
+                throw OCException(OC::Exception::NO_MEMORY, OC_STACK_NO_MEMORY);
+            }
+
+            strncpy(response.payload, payLoad.c_str(), payLoad.length()+1);
             response.payloadSize = payLoad.length() + 1;
             response.persistentBufferFlag = 0;
 
@@ -638,3 +646,4 @@ namespace OC
         OCStop();
     }
 }
+
index 6d72233..104ce42 100644 (file)
@@ -94,3 +94,4 @@ std::string OC::OCException::reason(const OCStackResult sr)
     return OC::Exception::UNKNOWN_ERROR;
 }
 
+
index 84ca4d8..ff20080 100644 (file)
@@ -226,3 +226,4 @@ namespace OC
         }
     } // namespace OCPlatform
 } //namespace OC
+
index 1df71a4..1ad68f9 100644 (file)
@@ -85,7 +85,7 @@ namespace OC
     OCPlatform_impl::OCPlatform_impl(const PlatformConfig& config)
      : m_cfg             { config },
        m_WrapperInstance { make_unique<WrapperFactory>() },
-       m_csdkLock        { make_shared<std::recursive_mutex>() }
+       m_csdkLock        { std::make_shared<std::recursive_mutex>() }
     {
         init(m_cfg);
     }
@@ -134,7 +134,7 @@ namespace OC
         return result_guard(
                    OCNotifyListOfObservers(resourceHandle,
                             &observationIds[0], observationIds.size(),
-                            reinterpret_cast<unsigned char *>(const_cast<char *>(payload.c_str())),
+                            payload.c_str(),
                             static_cast<OCQualityOfService>(QoS)));
     }
 
@@ -203,7 +203,7 @@ namespace OC
                                             uint8_t resourceProperty)
     {
         return checked_guard(m_server, &IServerWrapper::registerResource,
-                             ref(resourceHandle), resourceURI, resourceTypeName,
+                             std::ref(resourceHandle), resourceURI, resourceTypeName,
                              resourceInterface, entityHandler, resourceProperty);
     }
 
@@ -219,7 +219,8 @@ namespace OC
         std::vector<std::string> resourceTypes = resource->getResourceTypes();
 
         return checked_guard(m_server, &IServerWrapper::registerResourceWithHost,
-                ref(resourceHandle), resource->host(), resource->uri(), resourceTypes[0]/*"core.remote"*/, "oc.mi.def",
+                std::ref(resourceHandle), resource->host(), resource->uri(),
+                resourceTypes[0]/*"core.remote"*/, "oc.mi.def",
                 (EntityHandler) nullptr, resourceProperty);
     }
 
@@ -232,7 +233,7 @@ namespace OC
     OCStackResult OCPlatform_impl::unbindResource(OCResourceHandle collectionHandle,
                                             OCResourceHandle resourceHandle)
     {
-        return result_guard(OCUnBindResource(ref(collectionHandle), ref(resourceHandle)));
+        return result_guard(OCUnBindResource(std::ref(collectionHandle), std::ref(resourceHandle)));
     }
 
     OCStackResult OCPlatform_impl::unbindResources(const OCResourceHandle collectionHandle,
@@ -321,7 +322,7 @@ namespace OC
     OCStackResult OCPlatform_impl::unsubscribePresence(OCPresenceHandle presenceHandle)
     {
         return checked_guard(m_client, &IClientWrapper::UnsubscribePresence,
-                             ref(presenceHandle));
+                             std::ref(presenceHandle));
     }
 
     OCStackResult OCPlatform_impl::sendResponse(const std::shared_ptr<OCResourceResponse> pResponse)
@@ -330,3 +331,4 @@ namespace OC
                              pResponse);
     }
 } //namespace OC
+
index e4b71d2..d7950af 100644 (file)
@@ -112,9 +112,9 @@ namespace OC
         }
     }
 
-    void MessageContainer::setJSONRepresentation(const unsigned char* payload)
+    void MessageContainer::setJSONRepresentation(const char* payload)
     {
-        setJSONRepresentation(std::string(reinterpret_cast<const char*>(payload)));
+        setJSONRepresentation(std::string(payload));
     }
 
     std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const
@@ -973,3 +973,4 @@ namespace OC
         return os;
     }
 }
+
index ff96714..a0437f7 100644 (file)
@@ -340,7 +340,7 @@ OCResourceIdentifier::OCResourceIdentifier(const std::string& wireServerIdentifi
     }
 }
 
-ostream& operator <<(ostream& os, const OCResourceIdentifier& ri)
+std::ostream& operator <<(std::ostream& os, const OCResourceIdentifier& ri)
 {
 
     os << ri.m_representation<<ri.m_resourceUri;
@@ -382,3 +382,4 @@ bool OCResourceIdentifier::operator>=(const OCResourceIdentifier &other) const
 }
 
 } // namespace OC
+
index 75ab524..ab49be3 100644 (file)
@@ -20,7 +20,7 @@
 
 #include <OCApi.h>
 
-#include "OCUtilities.h"
+#include <OCUtilities.h>
 
 #include <boost/algorithm/string.hpp>
 
 #include <iterator>
 #include <algorithm>
 
-extern "C" {
-#include <uri.h>    // libcoap
-#include <option.h> // libcoap
-}
-
-namespace OC {
-
-    // Helper function to escape special character.
-    std::string escapeString(const std::string& value)
-    {
-        std::ostringstream stringStream;
-        for (const char& c : value)
-        {
-            switch (c)
-            {
-                case '\\': stringStream << "\\\\";
-                    break;
-                case '"': stringStream << "\\\"";
-                    break;
-                case '/': stringStream << "\\/";
-                    break;
-                case '\b': stringStream << "\\b";
-                    break;
-                case '\f': stringStream << "\\f";
-                    break;
-                case '\n': stringStream << "\\n";
-                    break;
-                case '\r': stringStream << "\\r";
-                    break;
-                case '\t': stringStream << "\\t";
-                    break;
-                default: stringStream << c;
-                    break;
-           }
-        }
-        return stringStream.str();
-    }
-}
-// [TODO] remove this function
-// it seems that the C stack is parsing and giving out the query separately.
-// the entire URI need not be parsed
-static OC::Utilities::QueryParamsKeyVal tempPatch(const std::string& _uri)
+OC::Utilities::QueryParamsKeyVal OC::Utilities::getQueryParams(const std::string& uri)
 {
     OC::Utilities::QueryParamsKeyVal qp;
-    if(_uri.empty())
+    if(uri.empty())
     {
         return qp;
     }
 
     std::vector<std::string> queryparams;
-    boost::split(queryparams, _uri, boost::is_any_of("&"));
+    boost::split(queryparams, uri, [](const char c){return c=='&';},
+    boost::token_compress_on);
 
     for(std::string& it: queryparams)
     {
-        std::vector<std::string> keyval;
-        boost::split(keyval, it, boost::is_any_of("="));
-        if(2 == keyval.size())
-        {
-            qp[keyval.at(0)] = keyval.at(1);
-        }
-    }
-
-    return qp;
-}
-
-// implementation can be split into two functions if needed
-// uses do{}while(0) to avoid returning from multiple locations
-OC::Utilities::QueryParamsKeyVal OC::Utilities::getQueryParams(const std::string& _uri)
-{
-
-    // this is a temporary fix. [TODO] remove this after permanent fix
-    return tempPatch(_uri);
-
-    OC::Utilities::QueryParamsKeyVal qp;
-    unsigned char *bufptr = nullptr; // don't delete via bufptr
-    unsigned char *bufptrToDelete = nullptr; // bufptr may be incremented. need this one to keep track.
-    do // while(0)
-    {
-        if(_uri.empty())
-        {
-            break;
-        }
-
-        coap_uri_t coapuri = {{0}};
-        unsigned char* uristr = reinterpret_cast<unsigned char*>(const_cast<char*>(_uri.c_str()));
+        auto index = it.find('=');
 
-        if(coap_split_uri(uristr, _uri.length(), &coapuri) < 0)
+        if(index == std::string::npos)
         {
-            break;
+            qp[it] = "";
         }
-
-        size_t buflen = 2048; // this is big enough buffer. [TODO] may want to downsize it. I have seen that the size may have to be greater than coap.query.length, which is counterintuitve but there may be a bug in coap uri parser.
-        bufptrToDelete = bufptr = new (std::nothrow) unsigned char[buflen](); // why heap? will need it for incrementing the pointer in the logic below
-
-        if(!bufptr)
+        else
         {
-            break;
-        }
-
-        int segments = -1;
-        if((segments = coap_split_query(coapuri.query.s, coapuri.query.length, bufptr, &buflen)) < 0)
-        {
-            break;
-        }
-
-        // coap uri parser has weird api. its not straighforward to understand what the coap function calls below do.
-        // coap uri parser lacks ability to split the key value pair in query params. that will be done in getQueryParams() function
-        std::vector<std::string> queryparams;
-        while(segments--)
-        {
-            queryparams.push_back(std::string (reinterpret_cast<char*>(coap_opt_value(bufptr)), coap_opt_length(bufptr)));
-            bufptr += coap_opt_size(bufptr);
-        }
-
-        if(queryparams.empty())
-        {
-            break;
-        }
-
-        //[TODO] use foreach
-        for(std::string& it : queryparams)
-        {
-            std::vector<std::string> keyval;
-            boost::split(keyval, it, boost::is_any_of("="));
-            if(2 == keyval.size())
-            {
-                qp[keyval.at(0)] = keyval.at(1);
-            }
+            qp[it.substr(0, index)] = it.substr(index + 1);
         }
     }
-    while(0);
-
-    if(bufptrToDelete)
-    {
-        delete [] bufptrToDelete;
+        return qp;
     }
-    return qp;
-}
 
 namespace OC {
 
@@ -214,3 +103,4 @@ OCStackResult result_guard(const OCStackResult r)
 }
 
 } // namespace OC
+
index e76c4e4..2966a60 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # OCLib (share library) build script
 ##
@@ -15,6 +35,7 @@ oclib_env.AppendUnique(CPPPATH = [
                '../include/',
                '../csdk/stack/include',
                '../csdk/ocrandom/include',
+               '../csdk/ocmalloc/include',
                '../csdk/logger/include',
                '../oc_logger/include',
                '../csdk/connectivity/lib/libcoap-4.1.1'
@@ -27,7 +48,7 @@ if target_os not in ['windows', 'winrt']:
 if target_os == 'android':
        oclib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
        oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-       oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'boost_thread-gcc-mt-1_49', 'gnustl_static', 'log'])
+       oclib_env.AppendUnique(LIBS = ['octbstack', 'oc_logger', 'boost_thread', 'gnustl_static', 'log'])
 
 if target_os in ['darwin', 'ios']:
        oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
@@ -51,3 +72,4 @@ oclib_src = [
 oclib_env.AppendUnique(CPPPATH = [oclib_env.get('SRC_DIR') + '/extlibs/cereal/include'])
 oclib = oclib_env.SharedLibrary('oc', oclib_src)
 oclib_env.InstallTarget(oclib, 'liboc')
+
index e02d6be..8f18728 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ######################################################################
 # This script manages third party libraries
 #
@@ -21,8 +41,8 @@ if target_os in ['linux', 'tizen']:
                if not target_arch == platform.machine():
                        print '''
 *********************************** Warning ***********************************
-* You are trying cross build, please make sure (%s) version libraries are
-* installed!                                                                 *
+* You are trying cross build, please make sure (%s) version libraries are     *
+* installed!                                                                  *
 *******************************************************************************
 ''' % target_arch
 
@@ -59,3 +79,4 @@ elif target_os == 'ios':
 elif target_os == 'darwin':
        lib_env.AppendUnique(CPPPATH = ['/usr/local/include'])
        lib_env.AppendUnique(LIBPATH = ['/usr/local/lib'])
+
index eadcf91..08e64e6 100644 (file)
@@ -1,10 +1,28 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # 'unit_test' script for building unit tests and libs
 #
 ##
 
-import os
-
 Import('env')
 
 target_os = env.get('TARGET_OS')
@@ -28,3 +46,4 @@ if target_os == 'linux':
        SConscript('unittests/SConscript')
 
 
+
index 841eaa0..2d23dbe 100644 (file)
@@ -25,3 +25,4 @@ It is not a system or end-to-end test.
 
 2. Run the unit test by issuing the following command from <oic-resource>:
    ./unittests/unittests
+
index ee442c6..c40e3c6 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 Import('env')
 import os
@@ -63,4 +82,4 @@ if env.get('TEST') == '1':
                unittests_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
                ut = unittests_env.Command ('ut', None,
                 [out_dir + '/resource/unittests/unittests'])
-               AlwaysBuild ('ut')
\ No newline at end of file
+               AlwaysBuild ('ut')
index 5be263d..ba374af 100644 (file)
@@ -87,3 +87,4 @@ $(MOCKS_DIR):
 clean:
        -rm -rf release
        -rm -rf debug
+
index 1ea7f78..6819e2d 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # 'service' sub-project main build script
 #
@@ -22,3 +42,4 @@ if target_os != 'arduino':
 #      SConscript('notification-manager/SConscript')
 #else:
 #      SConscript('notification-manager/SampleApp/arduino/SConscript')
+
index 26aa592..2c280f4 100644 (file)
@@ -28,3 +28,4 @@ SampleConsumer:       SampleConsumer.o
 
 clean:
        rm -f $(OBJS) SampleConsumer.o SampleProvider.o NotificationManager SampleProvider SampleConsumer
+
index 4c5dd05..a9b47fb 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # NotificationManager build script
 ##
@@ -45,3 +65,4 @@ notimgr_env.InstallTarget(notificationmanager, 'notificationmanager')
 
 # Go to build sample apps
 SConscript('SampleApp/SConscript')
+
index be46453..f21d4aa 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # NotificationManager build script
 ##
@@ -19,4 +39,5 @@ notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0',
 # Source files and Targets
 ######################################################################
 sampleprovider = notimgr_env.Program('sampleprovider', 'sampleProvider/SampleProvider.cpp')
-sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp')
\ No newline at end of file
+sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp')
+
index 2e33a43..5238429 100644 (file)
@@ -27,3 +27,4 @@ INSTALL(TARGETS ${EX_NOTIPROVIDER} DESTINATION ${BIN_INSTALL_DIR})
 ADD_EXECUTABLE(${EX_NOTICONSUMER} ${NOTI_BASE_DIR}/SampleApp/linux/sampleConsumer/SampleConsumer.cpp)
 TARGET_LINK_LIBRARIES(${EX_NOTICONSUMER} ${OCLIB} ${OCTBSTACK} pthread)
 INSTALL(TARGETS ${EX_NOTICONSUMER} DESTINATION ${BIN_INSTALL_DIR})
+
index e15658f..5b7461c 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # plugin-manager project build script
 ##
@@ -59,3 +79,4 @@ pmimpl_env.PrependUnique(LIBS = File(env.get('BUILD_DIR') + '/libcpluff.a'))
 pmimpl = pmimpl_env.SharedLibrary('pmimpl', pmimpl_src)
 
 plugin_manager_env.InstallTarget([ppm, pmimpl], 'libppm')
+
index 5e5d919..24b9fbe 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 ##
 # Plugins build script
 ##
@@ -18,7 +37,7 @@ plugins_env.AppendUnique(CPPPATH = ['../lib/cpluff/libcpluff'])
 
 if target_os not in ['windows', 'winrt']:
        plugins_env.AppendUnique(CXXFLAGS = ['-g3', '-Wall', '-pthread', '-std=c++0x'])
-       plugins_env.PrependUnique(CCFLAGS = ['-fPIC']) 
+       plugins_env.PrependUnique(CCFLAGS = ['-fPIC'])
        plugins_env.AppendUnique(LINKFLAGS = ['-fPIC'])
 
        if target_os not in ['arduino', 'android']:
@@ -44,3 +63,4 @@ mqtt_light_src = Glob('mqtt-light/src/' + '*.cpp')
 lightserver = plugins_env.SharedLibrary('mqtt-light/lightserver_mqtt_plugin', mqtt_light_src)
 
 SConscript('mqtt-fan/lib/SConscript')
+
index 0babef2..be886e9 100644 (file)
@@ -47,3 +47,4 @@ clean:
        cd ../../lib && $(MAKE) clean
        rm -rf ./release/obj
        cd ./release && rm -f *.so
+
index dbce34a..18cc4ad 100644 (file)
@@ -47,3 +47,4 @@ clean:
        cd ../../lib && $(MAKE) clean
        rm -rf ./release/obj
        cd ./release && rm -f *.so
+
index 3002f74..711f26b 100644 (file)
@@ -1,3 +1,22 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 ##
 #sample-app build script
 ##
@@ -26,7 +45,7 @@ sample_env.AppendUnique(LIBS = ['oc', 'oc_logger', 'octbstack',
                                                                'connectivity_abstraction', 'coap',
                                                                'ppm', 'pmimpl', 'dl'])
 
-if env.get('SECURED') == '1': 
+if env.get('SECURED') == '1':
     sample_env.AppendUnique(LIBS = ['tinydtls'])
 
 sample_env.ParseConfig('pkg-config --libs glib-2.0')
@@ -39,3 +58,4 @@ mqttclient = sample_env.Program('mqtt/mqttclient', 'mqtt/mqttclient.cpp')
 Alias('mqttclient', mqttclient)
 env.AppendTarget('mqttclient')
 
+
index d39f0ec..2114bad 100644 (file)
@@ -81,7 +81,7 @@ void onObserve(const HeaderOptions headerOptions, const OCRepresentation &rep,
     if (eCode == OC_STACK_OK)
     {
         std::cout << "OBSERVE RESULT:" << std::endl;
-        std::cout << "\tSequenceNumber: " << sequenceNumber << endl;
+        std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
 
         rep.getValue("state", myfan.m_state);
         rep.getValue("power", myfan.m_power);
@@ -132,9 +132,9 @@ void onPost2(const HeaderOptions &headerOptions, const OCRepresentation &rep, co
         }
 
         if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
-            std::cout << endl << "Observe is used." << endl << endl;
+            std::cout << std::endl << "Observe is used." << std::endl << std::endl;
         else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
-            std::cout << endl << "ObserveAll is used." << endl << endl;
+            std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
 
         //curFanResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve);
 
@@ -378,7 +378,7 @@ void foundResourceFan(std::shared_ptr<OCResource> resource)
     }
     catch (std::exception &e)
     {
-        //log(e.what());
+        std::cout<<"Exception in foundResourceFan: "<<e.what()<<std::endl;
     }
 }
 
@@ -436,7 +436,7 @@ void foundResourceLight(std::shared_ptr<OCResource> resource)
     }
     catch (std::exception &e)
     {
-        //log(e.what());
+        std::cout<<"Exception in foundResourceLight:" <<e.what() << std::endl;
     }
 }
 
@@ -636,9 +636,10 @@ int main(int argc, char *argv[])
     }
     catch (OCException &e)
     {
-        //log(e.what());
+        std::cout<<"Exception in main: "<<e.what() << std::endl;
     }
 
     return 0;
 }
 
+
index 777a79a..6143db6 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # soft-sensor-manager project build script
 ##
@@ -47,7 +67,7 @@ env.AppendTarget('libSSMSDK')
 libssmsdk = sdk_env.StaticLibrary(
                target = 'libSSMSDK',
                source = [ssm_sdk_cpp_src]
-               )               
+               )
 sdk_env.InstallTarget(libssmsdk, 'libSSMCORE')
 
 ######################################################################
@@ -125,3 +145,4 @@ if target_os == 'linux':
        Command("THSensorApp","SampleApp/linux/THSensorApp/THSensorApp", Copy("$TARGET", "$SOURCE"))
        Command("THSensorApp1","SampleApp/linux/THSensorApp1/THSensorApp1", Copy("$TARGET", "$SOURCE"))
 
+
index 9711461..e49d755 100644 (file)
@@ -82,3 +82,4 @@ clean:
        rm -f -v *.o ${TARGET}
        rm -rf ./${RST_NAME}
        
+
index 9dbb031..7693875 100644 (file)
@@ -410,3 +410,4 @@ JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterRepor
     if (reportReceiver != NULL)
         g_objReportReceiver = env->NewGlobalRef(reportReceiver);
 }
+
index 4f50e2b..52576fb 100644 (file)
@@ -84,4 +84,5 @@ JNIEXPORT void JNICALL Java_com_sec_android_ssmcore_CoreController_RegisterRepor
 }
 #endif
 
-#endif
\ No newline at end of file
+#endif
+
index de15320..43b052a 100644 (file)
@@ -202,7 +202,7 @@ OCEntityHandlerResult SSMResourceServer::entityHandler(std::shared_ptr< OCResour
 
         if (requestFlag & RequestHandlerFlag::RequestFlag)
         {
-            cout << "\t\trequestFlag : Request\n";
+            std::cout << "\t\trequestFlag : Request\n";
 
             // If the request type is GET
             if (requestType == "GET")
index 8e8666a..9a5e00e 100644 (file)
@@ -17,3 +17,4 @@ float CalculateExponentialAverage(int numberOfSamples, int* array, int startinde
 float calculateDistance(float avgRSSI, float txPower);
 
 #endif /* PROXIMITY_H_ */
+
index 5f851e7..5be062a 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # linux sample app  build script
 ##
@@ -18,7 +38,6 @@ linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 linux_sample_env.AppendUnique(LIBS = ['libSSMSDK'])
-#linux_sample_env.AppendUnique(LIBS = ['libSSMCORE'])
 linux_sample_env.AppendUnique(LIBS = ['libSSMCore'])
 linux_sample_env.AppendUnique(LIBS = ['pthread'])
 linux_sample_env.AppendUnique(LIBS = ['oc'])
@@ -39,3 +58,4 @@ linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 ssmtesterapp = linux_sample_env.Program('SSMTesterApp', 'src/SSMTestApp.cpp')
 Alias("ssmtesterapp_sample", ssmtesterapp)
 env.AppendTarget('SSMTesterApp')
+
index 40d0444..845e8f3 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # linux sample app  build script
 ##
@@ -33,3 +53,4 @@ linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 thsensorapp = linux_sample_env.Program('THSensorApp', 'src/ThingResourceServer.cpp')
 Alias("thsensorapp_sample", thsensorapp)
 env.AppendTarget('thsensorapp_sample')
+
index db51076..264d252 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # linux sample app  build script
 ##
@@ -23,7 +43,7 @@ linux_sample_env.AppendUnique(LIBS = ['liboc_logger'])
 linux_sample_env.AppendUnique(LIBS = ['pthread'])
 linux_sample_env.AppendUnique(LIBS = ['connectivity_abstraction'])
 linux_sample_env.AppendUnique(LIBS = ['coap'])
-if lib_env.get('SECURED') == '1': 
+if lib_env.get('SECURED') == '1':
     linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
 linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 
@@ -34,3 +54,4 @@ linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 thsensorapp1 = linux_sample_env.Program('THSensorApp1', 'src/ThingResourceServer1.cpp')
 Alias("thsensorapp1_sample", thsensorapp1)
 env.AppendTarget('thsensorapp1_sample')
+
index 2f789a5..9377b1f 100644 (file)
@@ -73,3 +73,4 @@ OCProject/
 â”‚   â””── OCServer.cpp :: TODO :: Unused remove??
 â””── README - You are reading this.
 
+
index c9f9a61..931376a 100644 (file)
@@ -96,3 +96,4 @@ The server and client can run in same machine or in different machines.
 
 5. To run simpleServer do \91./simpleServer\92 and to run simpleClient do \91./simpleClient\92.
 
+
index 118d960..43e841f 100644 (file)
@@ -67,3 +67,4 @@ clean: clean_legacy
        cd csdk && $(MAKE) deepclean
 clean_legacy:
        -rm -f -v OCLib.a *.o simpleserver simpleclient simpleclientserver
+
index 982cff1..e711d75 100644 (file)
@@ -49,3 +49,4 @@ INSTALL(TARGETS ${TESTAPP} DESTINATION ${BINDIR})
 #INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PKGNAME}.png DESTINATION "/usr/share/icons/default/small")
 INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PKGNAME}.xml DESTINATION "/usr/share/packages")
 INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PKGNAME}.rule DESTINATION /etc/smack/accesses2.d)
+
index 827571d..6dab7da 100644 (file)
@@ -51,3 +51,4 @@ cp -af %{SOURCE2} %{buildroot}/usr/apps/com.samsung.ssmtester/bin/
 /usr/share/*
 /etc/smack/accesses2.d/com.samsung.ssmtester.rule
 #%%license LICENSE.APLv2
+
index aed817c..0e098ee 100644 (file)
@@ -3,3 +3,4 @@ SET(SS_SAMPLE_PATH, "${SS_SRC_BASE}/SampleApp/linux");
 ADD_SUBDIRECTORY(ClientApp)
 ADD_SUBDIRECTORY(THSensorApp)
 ADD_SUBDIRECTORY(THSensorApp1)
+
index 86c8d89..330068d 100644 (file)
@@ -18,3 +18,4 @@ ADD_EXECUTABLE(${SS_SAMPLE_THSEN} ${SS_SAMPLE_THSEN_PATH}/src/ThingResourceServe
 TARGET_LINK_LIBRARIES(${SS_SAMPLE_THSEN} ${SS_SDK} ${OCLIB} ${OCTBSTACK} pthread)
 INSTALL(TARGETS ${SS_SAMPLE_THSEN} DESTINATION ${BIN_INSTALL_DIR})
 
+
index 192b8e1..2c2611e 100644 (file)
@@ -18,3 +18,4 @@ ADD_EXECUTABLE(${SS_SAMPLE_THSEN1} ${SS_SAMPLE_THSEN1_PATH}/src/ThingResourceSer
 TARGET_LINK_LIBRARIES(${SS_SAMPLE_THSEN1} ${SS_SDK} ${OCLIB} ${OCTBSTACK} pthread)
 INSTALL(TARGETS ${SS_SAMPLE_THSEN1} DESTINATION ${BIN_INSTALL_DIR})
 
+
index 412907c..9e80dcc 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # things_manager project build script
 ##
@@ -33,3 +53,5 @@ things_manager_env.InstallTarget(tgmsdk, 'libTGMSDK')
 
 #Go to build sample apps
 SConscript('sampleapp/SConscript')
+
+
index 7fe88ad..c8fa61c 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # sampleapp build script
 ##
index 0dfde14..5b0cb4c 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # linux sample app  build script
 ##
@@ -19,9 +39,9 @@ linux_sample_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 linux_sample_env.AppendUnique(CPPDEFINES = ['LINUX'])
 linux_sample_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
 linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack',
-                                                                               'connectivity_abstraction',
-                                                                               'libcoap', 'liboc_logger', 'dl', 'pthread'])
-if env.get('SECURED') == '1': 
+                                      'connectivity_abstraction',
+                                      'libcoap', 'liboc_logger', 'dl', 'pthread'])
+if env.get('SECURED') == '1':
     linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
 linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 
@@ -37,3 +57,4 @@ Alias("BootstrapServerApp", bootstrapserver)
 env.AppendTarget('ConServerApp')
 env.AppendTarget('ConClientApp')
 env.AppendTarget('BootstrapServerApp')
+
index 6701c82..f52d82d 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # linux sample app  build script
 ##
@@ -22,8 +42,8 @@ linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack',
                                                                                'connectivity_abstraction',
                                                                                'libcoap', 'liboc_logger', 'dl', 'pthread'])
 
-if env.get('SECURED') == '1': 
-    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+if env.get('SECURED') == '1':
+       linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
 
 linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 
@@ -39,3 +59,4 @@ Alias("BookmarkApp", bookmark)
 env.AppendTarget('GroupServerApp')
 env.AppendTarget('LightServerApp')
 env.AppendTarget('BookmarkApp')
+
index 9d866e6..8ce54f7 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ##
 # linux sample app  build script
 ##
@@ -22,8 +42,8 @@ linux_sample_env.AppendUnique(LIBS = ['libTGMSDKLibrary', 'oc', 'octbstack',
                                         'connectivity_abstraction',
                                         'libcoap', 'liboc_logger', 'dl', 'pthread'])
 
-if env.get('SECURED') == '1': 
-    linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
+if env.get('SECURED') == '1':
+       linux_sample_env.AppendUnique(LIBS = ['tinydtls'])
 
 linux_sample_env.ParseConfig('pkg-config --libs glib-2.0')
 
@@ -42,3 +62,4 @@ env.AppendTarget('GroupApp')
 env.AppendTarget('MusicplayerApp')
 env.AppendTarget('PhoneApp')
 env.AppendTarget('SpeakerApp')
+
index 0a194cc..0c077f9 100644 (file)
@@ -61,3 +61,4 @@ clean:
        rm -f -v *.o ${TARGET2}
        rm -f -v *.o ${TARGET3}
        rm -f -v *.o ${TARGET4}
+
index c87e9f1..5e52e06 100644 (file)
@@ -662,3 +662,4 @@ OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resour
     }
 }
 }
+
index b9cb9bd..46987d1 100644 (file)
@@ -30,6 +30,8 @@ using namespace OC;
 namespace OIC
 {
 
+    using std::cout;
+    using std::endl;
     GroupSynchronization* GroupSynchronization::groupSyncnstance = NULL;
 
     GroupSynchronization* GroupSynchronization::getInstance()
@@ -207,7 +209,7 @@ namespace OIC
         } catch(OCException &e) {
 
             return OC_STACK_INVALID_PARAM;
-            
+
         }
         cout << "GroupSynchronization::joinGroup : "
                 << "To bind collectionResHandle and resourceHandle" << endl;
@@ -378,7 +380,7 @@ namespace OIC
                                 << endl;
                         return result;
                     }
-                } catch(OCException &e) 
+                } catch(OCException &e)
                 {
                     cout << "ERROR : " << e.reason() << endl;
                     return OC_STACK_NO_RESOURCE;
@@ -1305,3 +1307,4 @@ namespace OIC
         }
     }
 }
+
index e1cbda4..165668d 100644 (file)
@@ -612,3 +612,4 @@ namespace OIC
         return g_groupmanager->findCandidateResources(type, &onFoundBootstrapServer);
     }
 }
+
index f979c89..3a79908 100644 (file)
@@ -1,3 +1,23 @@
+#******************************************************************
+#
+# Copyright 2014 Samsung Electronics All Rights Reserved.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 ######################################################################
 # This script manages third party libraries
 #
@@ -77,3 +97,4 @@ elif target_os == 'darwin':
 
 Import('env')
 lib_env.AppendUnique(LIBPATH = env.get('BUILD_DIR'))
+